Python Forum

Full Version: trying to edit a text file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Something very simple is causing me to pull my hair out.

I want to search a simple text file for a string and replace it with another string.

the text file reads

Output:
yipee wahooo whiffenhard yerp
my code reads:

f=open(r"fn", "r+")
for i in f:
    if "whiff" in i:
        f.write(i.replace(i, 'woo'))
        break
It appears to do nothing to the txt file.

Any help would be greatly appreciated.
Maybe something like this:
#! /usr/bin/env python3

import re
file = 'some.txt'

mylist = []
with open(file, 'r') as lines:
    print('----Original----')
    for line in lines:
        print(line.strip())
        new_line = re.sub('whiff', 'woo', line)
        mylist.append(new_line)

with open(file, 'w') as lines:
    for line in mylist:
        lines.write(f'{line.strip()}\n')

with open(file, 'r') as lines:
    print()
    print('----New File----')
    for line in lines:
        print(line.strip())
Output:
----Original---- yippe wahoo whiffenhard yerp ----New File---- yippe wahoo wooenhard yerp
(Dec-13-2021, 01:01 AM)menator01 Wrote: [ -> ]Maybe something like this:
#! /usr/bin/env python3

import re
file = 'some.txt'

mylist = []
with open(file, 'r') as lines:
    print('----Original----')
    for line in lines:
        print(line.strip())
        new_line = re.sub('whiff', 'woo', line)
        mylist.append(new_line)

with open(file, 'w') as lines:
    for line in mylist:
        lines.write(f'{line.strip()}\n')

with open(file, 'r') as lines:
    print()
    print('----New File----')
    for line in lines:
        print(line.strip())
Output:
----Original---- yippe wahoo whiffenhard yerp ----New File---- yippe wahoo wooenhard yerp



this is excellent thank you. i forgot to mention i am trying to replace the entire line as in replace "whiffenhard" with "woo" but i can likely play with what you gave me.
You can also do the same with the 'fileinput' module
from pathlib import Path
import fileinput

here = Path(__file__).parent

with fileinput.input((here/'fn.txt',), inplace=True) as fh:
    for line in fh:
        if 'whiff' in line:
            print('woo')
        else:
            print(line, end='')
Thanks for the replies. Does anyone know the reason my code doesn't work as intended? It just seems to do nothing to the txt file.
(Dec-13-2021, 05:09 PM)greatfella Wrote: [ -> ]Does anyone know the reason my code doesn't work as intended? It just seems to do nothing to the txt file.
Perhaps it is because you did not close() the file. Writing to a file is buffered. When the file is closed, the last buffered line(s) are written.
I tried many iterations, wish I could remember all of them to post. I just tried f.close() at the end and it still didn't work.
(Dec-14-2021, 12:36 AM)greatfella Wrote: [ -> ]I tried many iterations, wish I could remember all of them to post. I just tried f.close() at the end and it still didn't work.
It will not work as you try to do inplace of original file.
Look Gribouillis code it work as he use fileinput with inplace=True.
(Dec-14-2021, 12:36 AM)greatfella Wrote: [ -> ]i am trying to replace the entire line as in replace "whiffenhard" with "woo"
Output of Grib code in fn.txt:
Output:
yipee wahooo woo yerp
To get same output with menator01 code change line 9.
new_line = re.sub('whiffenhard', 'woo', line)
He dos a extra step make new list then overwrite original file,then avoid the inplace problem.

A third party module in-place
from in_place import InPlace.

with InPlace('fn.txt') as fp:
    for line in fp:
        line = line.replace('whiffenhard', 'woo')
        fp.write(line)
Output:
yipee wahooo woo yerp
sed is made for this.
(Dec-14-2021, 02:17 AM)snippsat Wrote: [ -> ]
(Dec-14-2021, 12:36 AM)greatfella Wrote: [ -> ]I tried many iterations, wish I could remember all of them to post. I just tried f.close() at the end and it still didn't work.
It will not work as you try to do inplace of original file.
Look Gribouillis code it work as he use fileinput with inplace=True.
(Dec-14-2021, 12:36 AM)greatfella Wrote: [ -> ]i am trying to replace the entire line as in replace "whiffenhard" with "woo"
Output of Grib code in fn.txt:
Output:
yipee wahooo woo yerp
To get same output with menator01 code change line 9.
new_line = re.sub('whiffenhard', 'woo', line)
He dos a extra step make new list then overwrite original file,then avoid the inplace problem.

A third party module in-place
from in_place import InPlace.

with InPlace('fn.txt') as fp:
    for line in fp:
        line = line.replace('whiffenhard', 'woo')
        fp.write(line)
Output:
yipee wahooo woo yerp

Thank you for the explanation, I was able to use Gribouillis' code and it worked.

Thanks again to everyone!