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
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).
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.