python: csv()--io.UnsupportedOpe
2020-05-15 本文已影响0人
山竹山竹px
目的:写入文件后直接读取文件
报错:不可读
with open('test.csv','w') as myfile: #打开文件,赋值为Myfile,准备写入
content = csv.writer(myfile) #调用writer
content.writerow(list_1)
print('写入完毕')
reader = csv.reader(myfile)
for i in reader:
print(i)
error:
for i in reader:
io.UnsupportedOperation: not readable
解决:
要先关闭文件,再次打开才能读取
with open('test.csv','w') as myfile: #打开文件,赋值为Myfile,准备写入
content = csv.writer(myfile) #调用writer
content.writerow(list_1) #按行写入
print('写入完毕')
with open('test.csv','r') as myfile:
reader = csv.reader(myfile)
for i in reader:
print(i)
另外,出现个小问题
上述代码的结果,出现了空白行
写入完毕
['1', '2', '3', '4', '5', '7']
[]
['32', '45', '65', '65', '35']
[]
['90', '5', '47']
[]
解决:
open()加上一个参数 open('test.csv','w',newline='')