from pandas import DataFrame
import numpy as np
df1 = DataFrame(np.arange(12).reshape((3,4)),columns = ['a','b','c','d'])
df1.to_csv('target.csv',encoding='utf-8')
python写csv文件会遇到两个问题,一个是csv文件每写入一行会自动空一行,一个是中文遇到的编码问题。
li1 = [1,2,3,4,5]
with open('target.csv', 'ab+') as f:
writer = csv.writer(f)
writer.writerow(li1)
# 或者
# f = open('target.csv', 'ab+')
li1 = [1,2,3,4,5]
with open('target.csv', 'a+', newline='') as f:
writer = csv.writer(f)
writer.writerow(li1)
# 或者
# f = open('target.csv', 'a+', newline='')
python3.6(以及相关版本,例3.5等)写入以编码为‘utf-8’中文时,虽然读的时候用‘utf-8’打开不影响中文编码,但用excel打开csv文件时,会出现中文乱码问题,因此采用编码为‘utf-8-sig’的方式写入,读文件时可用‘utf-8’打开,也可用‘utf-8-sig’打开。
li1 = [1,2,3,4,5]
with open('target.csv', 'a+', newline='', encoding='utf-8-sig') as f:
writer = csv.writer(f)
writer.writerow(li1)
# 或者
# f = open('target.csv', 'a+', newline='', encoding='utf-8-sig')
一般情况,我会用pandas的read_csv()方法打开csv文件。
import pandas as pd
df1 = pd.read_csv('target.csv',encoding='utf-8')
print(df1)