Reputation: 3
I'm trying to read a text file containing a list of user IDs and convert those IDs into email addresses by appending the @wherever.com ending to the IDs. Then I want to write those email addresses to a new file separated by commas.
textFile = open(“userID.txt”, “r”)
identList = textFile.read().split(“, “)
print identList
textFile.close()
emailString = “@wherever.com, ”
newList = [x + emailString for x in identList]
writeFile = open(“userEmail.txt”, “w”)
writeFile.writelines(newList)
writeFile.close()
I'm using python 3.x for Mac. This isn't working at all. I'm not sure if it is reading the initial file at all. It is certainly not writing to the new file. Can someone suggest where the program is failing to work?
Upvotes: 0
Views: 67
Reputation: 46759
Something like the following should work:
with open('userID.txt', 'r') as f_input, open('emails.txt', 'w') as f_output:
emails = ["{}@wherever.com".format(line.strip()) for line in f_input]
f_output.write(", ".join(emails))
So if you had a userID.txt
file containing the following names, with one name per line:
fred
wilma
You would get a one line output file as follows:
[email protected], [email protected]
Upvotes: 2
Reputation: 591
You could do it like this, also using context managers for reading and writing, because then you don't need to worry about closing the file:
identList = []
with open('userID.txt', 'r') as f:
identList = f.readlines().rstrip().split(',')
outString = ','.join([ '{0}@wherever.com'.format(x) for x in identList ])
with open('userEmail.txt', 'w') as f:
f.write(outString)
The conversion to string was done with join, which joins in this case the list elements formed in the comprehension with commas between them.
Upvotes: 0