【问题标题】:Python 2.7 delete line from text file [duplicate]Python 2.7从文本文件中删除行[重复]
【发布时间】:2017-03-12 13:05:17
【问题描述】:

在 Python 2.7 中,我正在使用..向文件写入一行。

f.write('This is a test')

如何删除这一行?文本文件中只有一行,所以我可以/应该删除该文件并创建一个新文件吗?

或者有没有办法删除我添加的行?

【问题讨论】:

标签: python python-2.7


【解决方案1】:

在 Python 中,您不能从文件中删除文本。相反,您可以写入文件。

write 函数有效地删除文件中的所有内容,并使用您作为参数传递的字符串保存文件。

例子

open_file=open("some file","w")
open_file.write("The line to write")

现在文件的内容为“要写入的行”。

编辑 write 函数更精确地从光标处写入。当您以 w 模式打开时,光标位于文件的前面并覆盖文件中的所有内容。

感谢 bli 指出这一点。

【讨论】:

  • 更准确地说,它是打开(在“w”模式下)和写入的组合。如果您在一个已经打开的文件中写入,这会将文本附加到您自 open 之后写入的任何内容。
【解决方案2】:

您可以删除文件并创建一个新文件或截断现有文件

# the original file
with open("test.txt", "w") as f:
    f.write("thing one")

# delete and create a new file - probably the most common solution
with open("test.txt", "w") as f:
    f.write("thing two")

    # truncate an existing file - useful for instance if a bit
    # of code as the file object but not file name
    f.seek(0)
    f.truncate()
    f.write("thing three")

# keep a backup - useful if others have the old file open
os.rename("test.txt", "test.txt.bak")
with open("test.txt", "w") as f:
    f.write("thing four")

# making live only after changes work - useful if your updates
# could fail
with open("test.txt.tmp", "w") as f:
    f.write("thing five")
os.rename('test.txt.tmp', 'test.txt')

哪个更好?它们都...取决于其他设计目标。

【讨论】:

    【解决方案3】:

    最佳做法是在打开文件时始终使用with,以确保即使您不调用close(),文件也将始终关闭

    with open('your_file', 'w') as f:
        f.write('new content')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-17
      • 1970-01-01
      • 2018-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-23
      相关资源
      最近更新 更多