How to modify a text file?

前端 未结 8 1395
不思量自难忘°
不思量自难忘° 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:57

    As mentioned by Adam you have to take your system limitations into consideration before you can decide on approach whether you have enough memory to read it all into memory replace parts of it and re-write it.

    If you're dealing with a small file or have no memory issues this might help:

    Option 1) Read entire file into memory, do a regex substitution on the entire or part of the line and replace it with that line plus the extra line. You will need to make sure that the 'middle line' is unique in the file or if you have timestamps on each line this should be pretty reliable.

    # open file with r+b (allow write and binary mode)
    f = open("file.log", 'r+b')   
    # read entire content of file into memory
    f_content = f.read()
    # basically match middle line and replace it with itself and the extra line
    f_content = re.sub(r'(middle line)', r'\1\nnew line', f_content)
    # return pointer to top of file so we can re-write the content with replaced string
    f.seek(0)
    # clear file content 
    f.truncate()
    # re-write the content with the updated content
    f.write(f_content)
    # close file
    f.close()
    

    Option 2) Figure out middle line, and replace it with that line plus the extra line.

    # open file with r+b (allow write and binary mode)
    f = open("file.log" , 'r+b')   
    # get array of lines
    f_content = f.readlines()
    # get middle line
    middle_line = len(f_content)/2
    # overwrite middle line
    f_content[middle_line] += "\nnew line"
    # return pointer to top of file so we can re-write the content with replaced string
    f.seek(0)
    # clear file content 
    f.truncate()
    # re-write the content with the updated content
    f.write(''.join(f_content))
    # close file
    f.close()
    

提交回复
热议问题