python中文件的打开与关闭,每次打开/关闭Python文件与保持打开状态直到过程完成...

I have about 50 GB of text file and I am checking the first few characters each line and writing those to other files specified for that beginning text.

For example.

my input contains:

cow_ilovecow

dog_whreismydog

cat_thatcatshouldgotoreddit

dog_gotitfromshelter

...............

So, I want to process them in cow, dog and cat (about 200) categories

so,

if writeflag==1:

writefile1=open(writefile,"a") #writefile is somedir/dog.txt....

writefile1.write(remline+"\n")

#writefile1.close()

so, what is the best way, should I close? Otherwise if I keep it open, is writefile1=open(writefile,"a") doing the right thing?

解决方案

You should definitely try to open/close the file as less as possible

Because even comparing with file read/write, file open/close is far more expensive

Consider two code blocks:

f=open('test1.txt', 'w')

for i in range(1000):

f.write('\n')

f.close()

and

for i in range(1000):

f=open('test2.txt', 'a')

f.write('\n')

f.close()

The first one takes 0.025s while the second one takes 0.309s

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值