写文件
写法1
import csv
csvfile=open('temp/csvfile.csv', 'w', newline='')
writer=csv.writer(csvfile)
writer.writerow('a')
writer.writerow('b')
csvfile.close()
写法2
import csv
with open('temp/csvfile.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow('a')
writer.writerow('b')
读文件
写法1
csvfile=open('temp/csvfile.csv', 'r', newline='')
txtdata=csvfile.read()
print(type(txtdata))
print(txtdata)
csvfile.close()
写法2
with open('temp/csvfile.csv', 'r', newline='') as f:
txtdata = f.read()
print(type(txtdata))
print(txtdata)
终端的命令行及输出结果
<user>python test.py
<class 'str'>
a
b
更多:https://blog.youkuaiyun.com/xrinosvip/article/details/82019844
特别注意
If csvfile is a file object, it should be opened with newline=’’.
更多:https://www.jianshu.com/p/0b0337df165a