-1

I've tried to write python code to do the following, and I'm stuck. Please help.

I have this file "names.txt"

rainbow like to play football

however rainbow ... etc

names = rainbow, john, alex 

rainbow sdlsdmclscmlsmcldsc.

I need to replace rainbow word to (Removed) in line which starts with "name = "

I need the code to search for keyword " name = " and replace the word "rainbow" to " (Removed") in the same line without changing the words rainbow in other lines, then overwrite the file "names.txt" with the changes to be like:

rainbow like to play football

however rainbow ... etc

names = (Removed), john, alex 

rainbow sdlsdmclscmlsmcldsc.

Thanks

Kshitij Saraogi
  • 6,821
  • 8
  • 41
  • 71
rainbow
  • 17
  • 1
  • show us the code, and are you checking for 'name =' or 'names =' – depperm Jan 04 '17 at 15:57
  • 1
    Welcome to Stack Overflow! You can take the [tour](http://stackoverflow.com/tour) first and learn [How to Ask a good question](http://stackoverflow.com/help/how-to-ask) and create a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example. It will be easier for us to help you. And please check your Grammar. – MrLeeh Jan 04 '17 at 15:59

2 Answers2

0

This will work in both Python 2.7 (which you used as a tag) and Python 3.

import fileinput
import sys

for line in fileinput.input("names.txt", inplace=1):
    if "names = " in line:
        line = line.replace("rainbow", "(Removed)")
    sys.stdout.write(line)

See "Optional in-place filtering" here (Python 2.7.13) or here (Python 3.6).

Spherical Cowboy
  • 565
  • 6
  • 14
-1

Avoiding regex, here is one way of doing it

with open("names.txt") as f:
  content = f.readlines()

This was stated in How do I read a file line-by-line into a list? and was found using google searching "stack overflow best way of reading in a file python". Then take this content, and do the following.

new_list_full_of_lines = [] # This is what you are going to store your corrected list with
for linea in content: # This is looping through every line
  if "names =" in linea:
    linea.replace ("rainbow", "(Removed)") # This corrects the line if it needs to be corrected - i.e. if the line contanes "names =" at any point
  new_list_full_of_lines.append(linea) # This saves the line to the new list
with open('names.txt', 'w') as f: # This will write over the file
  for item in new_list_full_of_lines: # This will loop through each line
    f.write("%s\n" % item) # This will ensure that there is a line space between each line.

Reference - String replace doesn't appear to be working

Other reference - Writing a list to a file with Python

Community
  • 1
  • 1
A. N. Other
  • 392
  • 4
  • 14