[Python]-pandas模块-CSV文件读写
Pandas 即Python Data Analysis Library,是为了解决数据分析而创建的第三方工具,它不仅提供了丰富的数据模型,而且支持多种文件格式处理,包括CSV、HDF5、HTML 等,能够提供高效的大型数据处理。
另外,csv模块也同样可以进行csv文件读写。
import pandas
import csv
pandas模块-读取CSV文件
import pandas
data = pandas.read_csv(csv_path)
# 查看前两行
print(data.head(2))
读到的数据为DataFrame结构。
csv_path可以是后缀为.csv或.txt
用.iterrows()方式读取某些列:
data = pandas.read_csv(csv_path)
# 按表头内容筛选某列
for index, row in data[['某列表头','某列表头']].iterrows():
    row1 = row[0]
    row2 = row[1]
csv模块-读取CSV文件
可以按列读取:
import csv
with open(csv_file,'r') as csvfile:
    data = csv.reader(csvfile)
	# 按列号筛选
    column = [row[3]for row in data]   #读取第4列
也可以全部读到list中便于操作:
with open(csv_path,'r') as csvfile:
    reader = csv.reader(csvfile)
	data = []
	for row in reader:
	data.append(row)
pandas模块-写入CSV文件
import pandas as pd
df = pd.DataFrame(data)
df.to_csv(csv_path)
csv模块-写入CSV文件
import csv
# 方法1
g = open(csv_path, 'w', encoding='utf-8', newline='')
csv_writer = csv.writer(g, delimiter=' ', quotechar=' ', quoting=csv.QUOTE_MINIMAL)
# 方法2
csv_writer.writerow(data)
详细参数参考:
http://t.zoukankan.com/xiaowangba9494-p-14355685.html
                    
                
                
            
        
浙公网安备 33010602011771号