Remove very last character in file

前端 未结 7 1780
说谎
说谎 2020-11-29 08:00

After looking all over the Internet, I\'ve come to this.

Let\'s say I have already made a text file that reads: Hello World

Well, I want to remo

相关标签:
7条回答
  • 2020-11-29 08:42
    with open('file.txt', 'w') as f:
        f.seek(0, 2)              # seek to end of file; f.seek(0, os.SEEK_END) is legal
        f.seek(f.tell() - 2, 0)  # seek to the second last char of file; f.seek(f.tell()-2, os.SEEK_SET) is legal
        f.truncate()
    

    subject to what last character of the file is, could be newline (\n) or anything else.

    0 讨论(0)
提交回复
热议问题