python - 写入文本文件时出现奇怪的空字符

标签 python python-3.x

我正在编写一个函数,将文本文件中的一行替换为用户输入的一行。

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.seekfile.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/

相关文章:

python - 从 Tensorflow/Keras 中的最佳神经网络中提取权重 - 多个时期

python - Python scrapy项目中传递全局变量的问题

python - TypeError:强制转换为 Unicode,需要字符串或缓冲区,找不到 NoneType

python - 为什么 Conda 不安装/更新最新版本的 Spyder?

python - 还记得在 Selenium 中单击过的元素文本吗?

python - 使用lxml代码解析HTML

Python:与 urljoin 混淆

python - 在递归函数中获取扫描目录和文件的绝对路径?

python - 将 SymPy 求解的方程解转化为函数时遇到问题

python - 使用 Python 比较两个不同的 csv 列时无法获取缺失的元素