Python - csv文件在使用csv writer后为空 [英] Python - csv file is empty after using csv writer
问题描述
这里是Python新手。我试图解决在一个更大的程序中编写csv文件的问题,并决定回到基础来尝试找到问题。
我运行了一个确切的代码示例来自Python csv读写文档:
import csv
spamWriter = csv.writer .csv','w'),delimiter ='',quotechar ='|')
spamWriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamWriter.writerow (['Spam','Lovely Spam','Wonderful Spam'])
我的工作目录并点击eggs.csv文件为空,报告为0 kb。同样的事情发生在我的较大的程序(空csv文件)。
编辑:
br>我刚刚尝试将代码修改为:
import csv
pre>
csvOut = open .csv,wb)
spamWriter = csv.writer(csvOut,delimiter ='',quotechar ='|')
spamWriter.writerow(['Spam'] * 5 + [' Beans'])
spamWriter.writerow(['Spam','Lovely Spam','Wonderful Spam'])
csvOut.close()
这个工作。我不知道为什么第一个不适合我。
解决方案我不太熟悉
csv
模块,但这看起来像一个文件IO问题比一个csv
问题。
在文件中看不到任何内容的原因是python仍然打开了该文件。
因此,不要这样做:
spamWriter = csv.writer(open('eggs.csv','w'),delimiter ='',quotechar ='|')
这样做:
f = open('eggs.csv','w ')
spamWriter = csv.writer(f,delimiter ='',quotechar ='|')
#其余代码
f.close()
现在你应该在eggs.csv看到你想要的东西
Hope这有助于
Python newbie here. I was trying to troubleshoot an issue with writing a csv file in a larger program and decided to go back to basics to try to find the problem.
I ran an exact code example from the Python csv reading and writing documention:
import csv spamWriter = csv.writer(open('eggs.csv', 'w'), delimiter=' ', quotechar='|') spamWriter.writerow(['Spam'] * 5 + ['Baked Beans']) spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
When I go to my working directory and click on "eggs.csv" the file is empty is reported as being "0 kb". This same thing was happening in my larger program (empty csv files). Am I missing something completely obvious?
Thank you!
EDIT:
I just tried modified the code to:import csv csvOut=open("eggs.csv", "wb") spamWriter = csv.writer(csvOut, delimiter=' ', quotechar='|') spamWriter.writerow(['Spam'] * 5 + ['Baked Beans']) spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam']) csvOut.close()
And this worked. I am not sure why the first doesn't work for me.
解决方案I'm not too familiar with the
csv
module, but this does look like a file IO problem more than acsv
problem.The reason that you see nothing in the file is that python still has the file open. You need to close it.
So rather than doing this:
spamWriter = csv.writer(open('eggs.csv', 'w'), delimiter=' ', quotechar='|')
Do this instead:
f = open('eggs.csv', 'w') spamWriter = csv.writer(f, delimiter=' ', quotechar='|') # the rest of your code f.close()
Now you should see what you want in eggs.csv
Hope this helps
这篇关于Python - csv文件在使用csv writer后为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!