How to edit a line in middle of txt file without overwriting everything?

前端 未结 1 875
日久生厌
日久生厌 2021-01-15 23:52

I have written a python script which read from a txt file and perform basic tasks like adding new line, deleting and editing existing lines. For deleting and editing, I load

相关标签:
1条回答
  • 2021-01-16 00:32

    The traditional solution is to copy the original file to a .sav file and then write the new edited version to the original filename:

    >>> import os
    >>> filename = 'somefile.txt'
    >>> with open(filename) as f:
            lines = f.readlines()
    >>> basename, ext = os.path.splitext(filename)
    >>> savefile = basename + '.sav'
    >>> os.rename(filename, savefile)
    >>> lines = map(str.upper, lines)    # do your edits here
    >>> with open(filename, 'w') as f:
            f.writelines(lines)
    
    0 讨论(0)
提交回复
热议问题