Read in file - change contents - write out to same file

后端 未结 2 1245
北荒
北荒 2021-01-01 12:59

I have to read in a file, change a sections of the text here and there, and then write out to the same file.

Currently I do:

f = open(file)
file_str          


        
2条回答
  •  孤独总比滥情好
    2021-01-01 13:32

    That looks straightforward, and clear already. Any suggestion depends on how big the files are. If not really huge that looks fine. If really large, you could process in chunks.

    But you could use a context manager, to avoid the explicit closes.

    with open(filename) as f:
        file_str = f.read()
    
    # do stuff with file_str
    
    with open(filename, "w") as f:
        f.write(file_str)
    

提交回复
热议问题