Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
trying to edit a text file
#1
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.
Yoriz write Dec-13-2021, 12:34 AM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
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
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#3
(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.
Reply
#4
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='')
Reply
#5
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.
Reply
#6
(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.
Reply
#7
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.
Reply
#8
(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
Gribouillis likes this post
Reply
#9
sed is made for this.
Gribouillis likes this post
Reply
#10
(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!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Thumbs Up Need to compare the Excel file name with a directory text file. veeran1991 1 1,279 Dec-15-2022, 04:32 PM
Last Post: Larz60+
  Modify values in XML file by data from text file (without parsing) Paqqno 2 1,888 Apr-13-2022, 06:02 AM
Last Post: Paqqno
  Converted Pipe Delimited text file to CSV file atomxkai 4 7,419 Feb-11-2022, 12:38 AM
Last Post: atomxkai
  [split] How to convert the CSV text file into a txt file Pinto94 5 3,582 Dec-23-2020, 08:04 AM
Last Post: ndc85430
  Saving text file with a click: valueerror i/o operation on closed file vizier87 5 4,689 Nov-16-2020, 07:56 AM
Last Post: Gribouillis
  saving data from text file to CSV file in python having delimiter as space K11 1 2,541 Sep-11-2020, 06:28 AM
Last Post: bowlofred
  Web Form to Python Script to Text File to zip file to web wfsteadman 1 2,250 Aug-09-2020, 02:12 PM
Last Post: snippsat
  Convert Excel file to Text file marvel_plato 6 20,454 Jul-17-2020, 01:45 PM
Last Post: marvel_plato
  Edit Json file mcmxl22 1 2,041 Apr-02-2020, 05:41 PM
Last Post: bowlofred
  Rename file from value in text file Nuge93 1 2,274 Jan-20-2020, 03:50 PM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020