python写csv文件前面的0消失_在python中写入csv文件(文件在操作结束时留空)

I am writing to csv in python, and I was wondering why my output files are blank when the program completes running. First off, here is my code:

reader = csv.reader(open(location, 'rU'), delimiter = ',', quotechar = '"')

writer = csv.writer(open('temp.csv', 'wb'), delimiter = ',', quotechar = '"')

writer.writerow(["test", "test", "test", "test", "test", "test", "test"])

count = 0

for row in reader:

if count != 0 and count < len(split):

writer.writerow([row[0], row[1], row[2], row[3], row[4], row[5], split[count-1]])

count = count + 1

I know a few things about it:

When the program finishes, all that is written to 'temp.csv' is the "test" line. The rest of the document is empty.

If I force stop the program in the middle of running, there is in fact text being written to the file: it just gets wiped for some reason.

I've done some research, and lots of people have found that "closing" the csv file solves their problems, but that doesn't seem to work for me, unless I am missing something obvious!

Thanks in advance for your help!

Edit: here is some updated code I am working with:

infile = open(location, 'rU')

outfile = open('temp.csv', 'wb')

reader = csv.reader(infile, delimiter = ',', quotechar = '"')

writer = csv.writer(outfile, delimiter = ',', quotechar = '"')

split = email_text.split('NEW MESSAGE BEGINS HERE')

count = 0

for row in reader:

if count != 0 and count < len(split):

writer.writerow([row[0], row[1], row[2], row[3], row[4], row[5], split[count-1]])

outfile.flush()

count = count + 1

infile.close()

outfile.close()

解决方案

You're not closing the file. While this may work fine if you're just reading a file, it's definitely not a good idea to do this when writing a file.

Use a context manager:

with open(location, 'rU') as infile, open('temp.csv', 'wb') as outfile:

reader = csv.reader(infile, delimiter = ',', quotechar = '"')

writer = csv.writer(outfile, delimiter = ',', quotechar = '"')

...

This ensures that the files will be closed when the with block is exited (even if it's because of an exception).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值