0

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?

3
  • 3
    What's your question? Commented Sep 2, 2015 at 16:24
  • You should look at the csv lib Commented Sep 2, 2015 at 16:43
  • Is this your real code? Because I don't think those fancy quotes are going to work. Commented Sep 2, 2015 at 17:48

2 Answers 2

2

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]
Sign up to request clarification or add additional context in comments.

7 Comments

This doesn't quite work. The output is: fred [email protected] The only the last entry has the email component appended and there are no commas separating entries.
It assumes your input file is a list of names, one per line. It could be changed to read a single line.
The input file actually is a list of names, one per line. The output is a list of names, one per line as well, but only the last name on the last line has the appended @wherever.com.
Are you sure the code is the same? I had made a small change shortly after posting.
It is exactly as it appears in your post above.
|
0

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.

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.