0

i am trying to replace text in file from a list in python, but got stuck and need some suggestion.

Basically, i am looking for text in replace_texts in each line of the file then save it using fileinput.

replace_texts = ['text 1','text 2']

for line in fileinput.input('file.txt', inplace=True):
    if any(text in line for text in replace_texts):
        # im not sure how to get the value variable from the if**
        replaced_line = line.replace(value, "something else")
        sys.stdout.write(replaced_line)
    else:
        sys.stdout.write(line)

file.txt

abctd fdskla fds
text 1 fdlald text 2
fdsa text 2 

and after run the code above. file.txt will become

abctd fdskla fds
something else fdlald something else
fdsa something else

Thanks,

4
  • What's your input file and the expected result? Do you want to split the input lines into words? Commented May 25, 2021 at 1:43
  • @BuddyBob please see my edit. Thank you Commented May 25, 2021 at 1:46
  • @prehistoricpenguin please see my edit. Thank you Commented May 25, 2021 at 1:46
  • so basically, i am looking for text 1, text 2 which is in replace_texts and replace with "something else" Commented May 25, 2021 at 1:48

2 Answers 2

2

The task is straightforward, just loop in the replace_texts to try to replace for each target.

The replace API will return a modified string, assign it to the line variable and continue the loop.

In the last print statement, we directly print the line variable, we don't care if it replaced or untouched.

import sys
replace_texts = ['text 1','text 2']

for line in open('file.txt'):
    for target in replace_texts:
        line = line.replace(target, "something else")
    sys.stdout.write(line)
Sign up to request clarification or add additional context in comments.

Comments

1

You were close, it was a good idea to first check if there are any occurrences of the word first. The part you were not sure about was, now that you check True or False for occurrences, if its True then you actually loop through your list.

Also if you are actually trying to write to a file, you will either need to use tempfile or write to a new file. The example below shows how you can use a context manager to open your old file and outputs a new file with replaced values.

replace_text = ['text 1','text 2']

#open the original file and output a new file with replaced values
with open('file 1.txt', 'r') as old, open('file 2.txt', 'w') as new:
    for line in old:
        if any(text in line for text in replace_text):
            #once you confirmed the word is in, then loop through list
            for text in replace_text:
                line = line.replace(text, 'something else')
        new.write(line)

Output in file 2.txt

abctd fdskla fds
something else fdlald something else
fdsa something else 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.