我正在编写一个函数,将文本文件中的一行替换为用户输入的一行。
def file_redact(file_name: str):
line_to_replace = int(input('Enter the line to replace (starting from 1): '))
f = open(file_name, 'r+')
file_data = f.readlines()
file_data[line_to_replace - 1] = input('Write a new line:\n') + '\n'
f.truncate(0)
f.writelines(file_data)
f.close()
Run Code Online (Sandbox Code Playgroud)
该函数做得很好,但是,它还在文件的开头添加了空字符。
这是我替换第一行后文件的样子:
\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00Replaced text
Sample text2
Sample text3
Sample text4
Sample text5
Run Code Online (Sandbox Code Playgroud)
任何帮助都会受到赞赏,特别是如果有更好的方法来实现这一点。
我想你误解了什么file.truncate。它调整文件大小,并显然用零字节或其他内容填充它。您想要的是file.seek,它会查找给定数字的当前写入和读取位置。当替换行比原始行短时,单独使用这可能会出现问题,因此您应该同时使用file.seek和file.truncate。这段代码的工作原理:
def file_redact(file_name: str):
line_to_replace = int(input('Enter the line to replace (starting from 1): '))
f = open(file_name, 'r+')
file_data = f.readlines()
file_data[line_to_replace - 1] = input('Write a new line:\n') + '\n'
f.truncate(0)
f.seek(0)
f.writelines(file_data)
f.close()
file_redact("test.txt")
Run Code Online (Sandbox Code Playgroud)