每次打开/关闭Python文件与保持打开直到进程完成

Ana*_*nta 26 python file-io

我有大约50 GB的文本文件,我正在检查每行的前几个字符,并将其写入为该起始文本指定的其他文件.

例如.我的输入包含:

cow_ilovecow
dog_whreismydog
cat_thatcatshouldgotoreddit
dog_gotitfromshelter
...............
Run Code Online (Sandbox Code Playgroud)

所以,我想在牛,狗和猫(约200个)类别中处理它们,所以,

if writeflag==1:
    writefile1=open(writefile,"a") #writefile is somedir/dog.txt....
    writefile1.write(remline+"\n")
    #writefile1.close()
Run Code Online (Sandbox Code Playgroud)

那么,什么是最好的方式,我应该关闭吗?否则,如果我保持开放,writefile1=open(writefile,"a")做正确的事情?

xva*_*tar 45

你绝对应该尝试尽可能少地打开/关闭文件

因为即使与文件读/写相比,文件打开/关闭也要贵得多

考虑两个代码块:

f=open('test1.txt', 'w')
for i in range(1000):
    f.write('\n')
f.close()
Run Code Online (Sandbox Code Playgroud)

for i in range(1000):
    f=open('test2.txt', 'a')
    f.write('\n')
    f.close()
Run Code Online (Sandbox Code Playgroud)

第一个需要0.025秒而第二个需要0.309秒

  • 显示绩效结果可加分! (2认同)

Ash*_*ary 5

使用该with语句,它会自动为您关闭文件,执行with块内的所有操作,因此它会为您打开文件,并在您离开with块时关闭文件.

with open(inputfile)as f1, open('dog.txt','a') as f2,open('cat.txt') as f3:
   #do something here
Run Code Online (Sandbox Code Playgroud)

编辑: 如果您知道在编译代码之前要使用的所有可能的文件名,那么使用with是一个更好的选项,如果您不这样做,那么您应该使用您的方法,但不是关闭文件,您可以flush使用数据到文件writefile1.flush()