How to modify a text file?

前端 未结 8 1399
不思量自难忘°
不思量自难忘° 2020-11-22 03:14

I\'m using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?

8条回答
  •  再見小時候
    2020-11-22 03:38

    The fileinput module of the Python standard library will rewrite a file inplace if you use the inplace=1 parameter:

    import sys
    import fileinput
    
    # replace all occurrences of 'sit' with 'SIT' and insert a line after the 5th
    for i, line in enumerate(fileinput.input('lorem_ipsum.txt', inplace=1)):
        sys.stdout.write(line.replace('sit', 'SIT'))  # replace 'sit' and write
        if i == 4: sys.stdout.write('\n')  # write a blank line after the 5th line
    

提交回复
热议问题