我正在编写一个函数,将文本文件中的一行替换为用户输入的一行。
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()
该函数可以很好地执行此操作,但是,它还在文件开头添加了空字符。这是我替换第一行后文件的样子:
\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\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
任何帮助表示赞赏,特别是如果有更好的方法来实现这一点。
最佳答案
我想你误会了什么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")
关于python - 写入文本文件时出现奇怪的空字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66391727/