Probably a simple question, but I am new to Python. I have a file containing email addresses, one per line. I want to read the file and append them together separated by a comma. Is there a more pythonic way of doing this?
def getEmailList(file_name):
f = open(file_name, 'r')
emailstr = ''
for line in f:
emailstr += line.rstrip() + ','
f.close()
return emailstr
You could do the following:
def getEmailList(file_name):
with open(file_name) as f:
return ",".join(x.rstrip() for x in f)
The key features of that version are:
with statement so that the file is automatically closed when control leaves that block.x.rstrip() for x in f to strip each line Thanks to agf for that correctionstr.join to put a ',' between each item in the sequenceIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With