Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python List Parsing

Tags:

python

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
like image 794
EdgeCase Avatar asked Jan 17 '26 20:01

EdgeCase


1 Answers

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:

  • Using the with statement so that the file is automatically closed when control leaves that block.
  • Using the list comprehension generator expression x.rstrip() for x in f to strip each line Thanks to agf for that correction
  • Using str.join to put a ',' between each item in the sequence
like image 168
Mark Longair Avatar answered Jan 20 '26 08:01

Mark Longair



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!