How to modify a text file?

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

    Rewriting a file in place is often done by saving the old copy with a modified name. Unix folks add a ~ to mark the old one. Windows folks do all kinds of things -- add .bak or .old -- or rename the file entirely or put the ~ on the front of the name.

    import shutil
    shutil.move( afile, afile+"~" )
    
    destination= open( aFile, "w" )
    source= open( aFile+"~", "r" )
    for line in source:
        destination.write( line )
        if :
            destination.write( >some additional line> + "\n" )
    source.close()
    destination.close()
    

    Instead of shutil, you can use the following.

    import os
    os.rename( aFile, aFile+"~" )
    

提交回复
热议问题