Reputation: 13
Suppose I have a below text file called file1.txt:
Adam male
John male
Mike male
Sue female
and I have the below list
fullname=['John Smith', 'Sue Hunt']
I want to be able go though the text file, and if it there is any matching there, amend the line with the word found, output should look like below:
Adam male
John male found
Mike male
Sue female found
so I got this code, but the replace function don;t seem to be right
f=open(file1.txt,'a')
for line in f:
for name in fullname:
firstname,lastname=name.split('--')
if firstname in line:
line.replace('\n', 'found\n')
Upvotes: 0
Views: 53
Reputation: 12935
This sounds like a work in progress, so I'd prepare for future modifications by creating two dictionaries of the names
and genders
that can be consulted later on and writing a new output file, so as not to corrupt the source file.
# python 3.6+
import re
fullname=['John Smith', 'Sue Hunt']
names = { re.split('\W+', line)[0]:re.split('\W+', line)[1] for line in fullname }
with open('file1.txt', 'r') as f:
file=f.read().splitlines()
genders = { re.split('\W+', line)[0]:re.split('\W+', line)[1] for line in file }
with open('results.txt', 'w') as f:
for k,v in genders.items():
if k in names.keys():
f.write(f"{k} {v} found \n")
else:
f.write(f"{k} {v} \n")
cat results.txt
Adam male
John male found
Mike male
Sue female found
Upvotes: 0
Reputation: 4528
The replace
function doesn't work inplace :
Return a copy of the string with all occurrences...
line = line.replace('\n', 'found\n')
Upvotes: 1
Reputation: 82765
Try:
fullname=['John Smith', 'Sue Hunt']
fname = [i.split()[0] for i in fullname]
res = []
with open(filename) as infile:
for line in infile:
if line.split()[0] in fname:
res.append("{} Found \n".format(line.strip()))
else:
res.append(line)
with open(filename, "w") as outfile:
for line in res:
outfile.write(line)
Upvotes: 0