probably-asskicker
probably-asskicker

Reputation: 171

Trying to read a data from another file in python

I am trying to make my code read the data from a different file. The data in the file emaillist.txt is written in the following format:

a
b
b
c
s
f
s

Now I am tryin to pick a random email from this file and I am getting an error. Here is the code {Note: this is a piece of code, I have imported the correct libraries}:

with open('emaillist.txt') as emails:
                read_emails = csv.reader(emails, delimiter = '\n')
        for every_email in read_emails:
                return random.choice(every_email)

and this is the error:

Traceback (most recent call last):
  File "codeOffshoreupdated.py", line 56, in <module>
    'email': email_random(),
  File "codeOffshoreupdated.py", line 12, in email_random
    for every_email in read_emails:
ValueError: I/O operation on closed file.

Can you please help me fix it? It will be very helpful. Thanks in advance

Upvotes: 1

Views: 46

Answers (2)

Leo Arad
Leo Arad

Reputation: 4472

This code will return you a random email from the emilas that in the file because in your code is returning the first email from the file since it is the first iteration of for every_email in read_emails:

with open('emaillist.txt') as emails:
     read_emails = csv.reader(emails, delimiter = '\n')
     return random.choice(list(read_emails))[0]

Upvotes: 1

Ben Stobbs
Ben Stobbs

Reputation: 432

Indent your for loop, like this:

with open('emaillist.txt') as emails:
                read_emails = csv.reader(emails, delimiter = '\n')
                for every_email in read_emails:
                        return random.choice(every_email)

Upvotes: 1

Related Questions