Johnny Bravo
Johnny Bravo

Reputation: 19

change a string in a file with python

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

Upvotes: 0

Views: 241

Answers (3)

Johnny Bravo
Johnny Bravo

Reputation: 19

The answer (thanks to @Constantin and @Thierry Lathuille):

  • Execute in python3: for some reason import os doesn't work in 2.x
  • Change the targeted file encoding (e.g. UTF-8)

Upvotes: 1

Constantin
Constantin

Reputation: 915

The function call is correct, although you may have something conflicting with the module os in your file. I suggest importing os.replace this way:

from os import replace

If it is still conflicting you could import the replace function to as you want, like:

from os import replace as rename_file

Upvotes: 1

Unused hero
Unused hero

Reputation: 307

You actually trying to rename the file.
You should use os.rename() method, so your code will be:

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')

Upvotes: 1

Related Questions