使用python更改文件中的字符串



我正在尝试使用python更改文本文件。删除包含特定字符串

的每一行我在使用操作系统时遇到了一个错误。替代方法。

Traceback (most recent call last):
File "test.py", line 12, in <module>
os.replace('/home/johnny/Documents/Python/temp.txt', '/home/johnny/Documents/Python/Soothing.txt')
AttributeError: 'module' object has no attribute 'replace'

这是我的代码:

import os
with open("/home/johnny/Documents/Python/Soothing.txt", "r") as input:
with open("/home/johnny/Documents/Python/temp.txt", "w") as output:
# iterate all lines from file
for line in input:
# if line starts with given substring then don't write it in temp file
if not line.strip("n").startswith('stuff i dont like'):
output.write(line)
# replace file with original name
os.replace('/home/johnny/Documents/Python/temp.txt', '/home/johnny/Documents/Python/Soothing.txt')

代码是file.py格式,我在Linux shell中执行。

试图找出哪里出错了,我试了:

-在linux shell中导入操作系统无效,输入import os

-将目录更改为简单的文件名==>No good either

这个东西的输出是一个临时文件,执行了适当的更改,但我无法重写原始文件

欢迎任何帮助

p>

OS: linux (ubuntu 18.04)

-python 2.7.17将其混联到3.6.9,正如这里所解释的,它变得更糟,并给出:

Traceback (most recent call last):
File "test.py", line 6, in <module>
for line in input:
File "/usr/lib/python3.6/codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe8 in position 253: invalid continuation byte

然后我试了python3 test.py==>同样的错误

您实际上试图重命名文件。
你应该使用os.rename()方法,所以你的代码将是:

import os
with open("/home/johnny/Documents/Python/Soothing.txt", "r") as input:
with open("/home/johnny/Documents/Python/temp.txt", "w") as output:
# iterate all lines from file
for line in input:
# if line starts with given substring then don't write it in temp file
if not line.strip("n").startswith('stuff i don't like'):
output.write(line)
# replace file with original name
os.rename('/home/johnny/Documents/Python/temp.txt', '/home/johnny/Documents/Python/Soothing.txt')

函数调用是正确的,尽管您可能与文件中的模块os有冲突。我建议这样导入os.replace:

from os import replace

如果仍然存在冲突,您可以根据需要导入replace函数,如:

from os import replace as rename_file

答案(感谢@Constantin和@Thierry Lathuille):

  • 在python3中执行:由于某些原因import os不能在2.x中工作
  • 更改目标文件编码(例如UTF-8)

最新更新