i'm trying to change a text file using python. removing every line that contains a certain string
i stumble on an error using the os.replace method.
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'
here's my code:
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')
the code is in a file.py format i execute in a linux shell.
trying to figure out what goes wrong, i tried:
-importing os in the linux shell to no avail, typing import os
-changing the directory to a simple file name ==> no good either
the output of the thingy is a temp file with the proper change performed but i'm unable to rewrite the original file
any help's welcome.
PS
-OS: linux (ubuntu 18.04)
-python 2.7.17 aliasing it to 3.6.9 as explained here it gets worse and gives:
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
then i tried python3 test.py==> same error
os.pysomewhere?print(os.__file__)?python my_code.py, than trypython3 my_code.py. Maybe you could specify the Python version number you're using in your question.pip freeze > requirements.txt?open("/home/johnny/Documents/Python/Soothing.txt", encoding=<your actual encoding>). You have a list of the standard encodings at docs.python.org/3/library/codecs.html#standard-encodings