Python 2.7从文本文件中删除行
在Python2.7中,我正在使用..向文件中写入一行Python 2.7从文本文件中删除行,python,python-2.7,Python,Python 2.7,在Python2.7中,我正在使用..向文件中写入一行 f.write('This is a test') 如何删除此行?文本文件中只有一行,因此我是否可以/应该删除该文件并创建一个新文件 或者有没有办法删除我添加的行?在Python中,不能从文件中删除文本。相反,您可以写入文件 write函数有效地删除文件中的任何内容,并使用作为参数传递的字符串保存文件 范例 open_file=open("some file","w") open_file.write("The line to write
f.write('This is a test')
如何删除此行?文本文件中只有一行,因此我是否可以/应该删除该文件并创建一个新文件
或者有没有办法删除我添加的行?在Python中,不能从文件中删除文本。相反,您可以写入文件 write函数有效地删除文件中的任何内容,并使用作为参数传递的字符串保存文件 范例
open_file=open("some file","w")
open_file.write("The line to write")
现在文件的内容是“要写入的行”
编辑
write函数更精确地从光标所在的位置进行写操作。在w模式下打开时,光标位于文件前面,并覆盖文件中的所有内容。感谢bli指出这一点。您可以删除该文件并创建一个新文件或截断现有文件
# 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')
哪个更好?他们都是。。。取决于其他设计目标。在打开文件时始终使用
和
,以确保即使不调用close()
--使用f.truncate()更准确地说,它是打开(在“w”模式下)和写入的组合。如果您在已打开的文件中写入,这将在
打开后写入的任何文件中追加文本。
with open('your_file', 'w') as f:
f.write('new content')