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

后端 未结 2 1247
北荒
北荒 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:45

    If you work line by line you can use fileinput with inplace mode

    import fileinput
    
    for line in fileinput.input(mifile, inplace=1):
        print process(line)
    

    if you need to process all the text at once, then your code can be optimized a bit using with that takes care of closing the file:

    with open(myfile) as f:
        file_str = f.read()
    #
    do_actions_on_file_str
    #
    with open(myfile, 'w') as f:
        f.write(file_str)
    

提交回复
热议问题