How to modify a text file?

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

    Python's mmap module will allow you to insert into a file. The following sample shows how it can be done in Unix (Windows mmap may be different). Note that this does not handle all error conditions and you might corrupt or lose the original file. Also, this won't handle unicode strings.

    import os
    from mmap import mmap
    
    def insert(filename, str, pos):
        if len(str) < 1:
            # nothing to insert
            return
    
        f = open(filename, 'r+')
        m = mmap(f.fileno(), os.path.getsize(filename))
        origSize = m.size()
    
        # or this could be an error
        if pos > origSize:
            pos = origSize
        elif pos < 0:
            pos = 0
    
        m.resize(origSize + len(str))
        m[pos+len(str):] = m[pos:origSize]
        m[pos:pos+len(str)] = str
        m.close()
        f.close()
    

    It is also possible to do this without mmap with files opened in 'r+' mode, but it is less convenient and less efficient as you'd have to read and temporarily store the contents of the file from the insertion position to EOF - which might be huge.

    0 讨论(0)
  • 2020-11-22 04:03

    Depends on what you want to do. To append you can open it with "a":

     with open("foo.txt", "a") as f:
         f.write("new line\n")
    

    If you want to preprend something you have to read from the file first:

    with open("foo.txt", "r+") as f:
         old = f.read() # read everything in the file
         f.seek(0) # rewind
         f.write("new line\n" + old) # write the new line before
    
    0 讨论(0)
提交回复
热议问题