简体   繁体   中英

File has zero lines in else block of python try except code

I have a simple python code to open the.csv file and check for exceptions. The file exists in my current folder and it has more than 2 lines of data. But the for loop in the else part is not executing.. because I'm getting zero lines to count.

# Base class for defining your own user-defined exceptions.
class Error(Exception):
    '''Base class for other exceptions'''
    pass

# own exception class as a subclass of error
class EmptyFileError(Error):
    pass
# raise error
try:
    # open the file (no error check for this example).
    thefile = open('people.csv')
    # count the number of lines in file.
    file_content = thefile.readlines()
    line_count = len(file_content)
    # If there is fewer than 2 lines, raise exception.
    if line_count < 2:
        raise EmptyFileError
# Handles missing file error.
except FileNotFoundError:
    print('\n There is no people.csv file here')
# Handles my custom error for too few rows.
except EmptyFileError:
    print('\nYour people.csv does not have enough stuff')
# Handles all other Exceptions
except Exceptions as e:
    # Show the error
    print('\n\nFailed: The error was '+str(e))
    # Close the file
    thefile.close()
else:
    print(thefile.name)
    # file must be open if we got here
    for one_line in file_content:
        print(list(one_line.split(',')))
    thefile.close()
    print('Success')

I was able to see the output of the file name and success message from the else part but not the for loop part. There were no exceptions occurred and so the file was never closed before else part. What could be the problem?

Solved with the help of @Ralf answer.

You already consumed all the lines of the file by calling thefile.readlines() ; when you start the loop for one_line in thefile: there are no more lines to read, so the loop never gets executed.

Possible solution: use a variable to hold the file contents.

line_list = thefile.readlines()
line_count = len(line_list)

and the iterate over that:

for one_line in line_list:

Here are some related questions with more info:

Read multiple times lines of the same file Python

Why can't I call read() twice on an open file?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM