文件在python try-except代码的else块中没有行

文件在python try-except代码的else块中没有行,python,python-3.x,exception,error-handling,Python,Python 3.x,Exception,Error Handling,我有一个简单的python代码来打开.csv文件并检查异常。 该文件存在于我的当前文件夹中,并且有两行以上的数据。 但是else部分中的for循环没有执行。。因为我要数到零行 # Base class for defining your own user-defined exceptions. class Error(Exception): '''Base class for other exceptions''' pass # own exception class as a

我有一个简单的python代码来打开.csv文件并检查异常。 该文件存在于我的当前文件夹中,并且有两行以上的数据。 但是else部分中的for循环没有执行。。因为我要数到零行

# 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')
#用于定义自己的用户定义异常的基类。
类错误(异常):
''其他异常的基类''
通过
#将自己的异常类作为错误的子类
类EmptyFileError(错误):
通过
#提出错误
尝试:
#打开文件(本例无错误检查)。
thefile=open('people.csv')
#计算文件中的行数。
file_content=thefile.readlines()
行计数=len(文件内容)
#如果少于2行,则引发异常。
如果行_计数小于2:
raise EmptyFileError
#处理丢失的文件错误。
除FileNotFoundError外:
打印(“\n此处没有people.csv文件”)
#处理太少行的自定义错误。
除EmptyFileError外:
打印(“\n您的people.csv没有足够的内容”)
#处理所有其他异常
例外情况除外,例如:
#显示错误
打印('\n\n失败:错误为'+str(e))
#关闭文件
thefile.close()文件
其他:
打印(文件名)
#如果我们到了这里,文件必须打开
对于文件内容中的一行:
打印(列表(一行分割(','))
thefile.close()文件
打印(‘成功’)
我能够看到来自else部分的文件名和成功消息的输出,但不能看到for循环部分。没有发生任何异常,因此该文件从未在else部分之前关闭。 有什么问题吗


在@Ralf answer的帮助下解决了问题。

通过调用
thefile.readlines()
,您已经使用了文件的所有行;当您为文件中的一行启动循环时:没有更多的行可读取,因此循环永远不会执行

可能的解决方案:使用变量保存文件内容

line_list = thefile.readlines()
line_count = len(line_list)
然后再重复一遍:

for one_line in line_list:

以下是一些相关问题和更多信息:


是的。它像冠军一样成功。谢谢你的帮助。我不熟悉文件处理模块。谢谢你的推荐@Ralf。