美文网首页
python: csv()--io.UnsupportedOpe

python: csv()--io.UnsupportedOpe

作者: 山竹山竹px | 来源:发表于2020-05-15 16:05 被阅读0次

目的:写入文件后直接读取文件

报错:不可读

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='')

相关文章

网友评论

      本文标题:python: csv()--io.UnsupportedOpe

      本文链接:https://www.haomeiwen.com/subject/grgcohtx.html