python 使用csv.reader和csv.writer读写文件并转换成dataframe格式

import csv
import pandas as pd

###csv.reader用法
'''
f=open(r"C:\Users\admin\pycdtest\wanyue\yueeceshi.csv")
readeriter=csv.reader(f)
for line in readeriter:
    print(line)
'''
lines=list(csv.reader(open(r"C:\Users\admin\pycdtest\wanyue\yueeceshi.csv")))
header,values=lines[0],lines[1:]
data_dict={h:v for h,v in zip(header,zip(*values))}
#print(data_dict)
df=pd.DataFrame(data_dict)#转换成dataframe格式

'''
#定义csv.Dialect子类,应对不同新csv新格式
class my_dialect(csv.Dialect):
    lineterminator='\n'#行结束符标识
    delimiter=','#分隔符
    quotechar='"'#字符串引用约定符

readeriter=csv.reader(f,diaect=my_dialet)
#readeriter=csv.reader(f,delimiter=',')
'''

###csv.writer用法
print(df.head())
rows = df.values
with open('my.csv', 'w+', newline='') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(df.columns)
    for row in rows:
        writer.writerow(row)

 详解参照http://blog.csdn.net/u011284860/article/details/51031051 

posted on 2018-02-24 12:44  hailuo  阅读(5952)  评论(0编辑  收藏  举报