Python file open/close every time vs keeping it open until the process is finished

后端 未结 4 1669
暗喜
暗喜 2020-12-24 11:29

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.

4条回答
  •  清歌不尽
    2020-12-24 12:02

    Use the with statement, it automatically closes the files for you, do all the operations inside the with block, so it'll keep the files open for you and will close the files once you're out of the with block.

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

    EDIT: If you know all the possible filenames to be used before the compilation of your code then using with is a better option and if you don't then you should use your approach but instead of closing the file you can flush the data to the file using writefile1.flush()

提交回复
热议问题