0
import fileinput

with fileinput.FileInput('FILE_PATH_ON_MY_COMPUTER', inplace=True, backup='') as file:
    for line in file:
        print(line.replace(", uh,", ""), end='')
    for line in file:
        print(line.replace(", uh", ""), end='')
    for line in file:
        print(line.replace(" uh,", ""), end='')

I am trying to use the fileinput library to find and replace the matching text in a txt file. I would like it to find and replace multiple strings, not just one. Thus, I tried to put it all into one program. However, when I have a separate for loop for each print statement (as shown in the code), it only replaces the first keyword. When I keep one for loop and have all the print lines under it, the resulting txt file is a massive mess of repeated lines vertically spaced far apart. How do I get the program to find and replace multiple items without failing? What is the logical error in my code?

Thanks for the help

  • 1
    `file` is likely to be an iterator (have not looked into the documentation), thus you cannot iterate over it multiple times. Use `itertools.tee(...)` or do all the replacements in the same iteration. – Jan Apr 22 '20 at 13:53

2 Answers2

1

file is an iterator, thus you cannot iterate over it multiple times.


Either use
from itertools import tee
file1, file2, file3 = tee(file, n=3)

Or just do all the replacements in one go:

for line file:
    print(line.replace(", uh,", ""), end='').replace(", uh", ""), end='').replace(" uh,", ""), end=''))

Or (preferable) use a regular expression like

import re
rx = re.compile(r',? uh,?')

for line in file:
    print(rx.sub('', line))
Jan
  • 38,539
  • 8
  • 41
  • 69
0

You can use standard regex replace in files:

import re


regex = r"(,|)(\s|)uh"

with open('test.txt', 'r') as f:
    content = f.read()
    new_content = re.sub(regex, '', content)
    with open('test.txt', 'w') as target:
        target.write(new_content)

Suggestions on nicer file handling appreciated

This will transform:

need, uh some
some uh need
heheuheheh need uhneed some

To:

need some
some need
heheeheh needneed some
Alex Smith
  • 192
  • 1
  • 10
  • a) You forgot the last comma (`uh,`) and b) there's no need for parentheses in the expression as you're not doing anything with the groups anyway. – Jan Apr 22 '20 at 14:10