gpt4 book ai didi

python - 文件在 python try 的 else block 中有零行,除了代码

转载 作者:行者123 更新时间:2023-12-03 07:41:28 25 4
gpt4 key购买 nike

我有一个简单的 python 代码来打开 .csv 文件并检查异常。
该文件存在于我当前的文件夹中,并且有超过 2 行的数据。
但是 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')

我能够从 else 部分看到文件名和成功消息的输出,但没有看到 for 循环部分。没有发生异常,因此文件从未在 else 部分之前关闭。
可能是什么问题呢?

已解决 在@Ralf 回答的帮助下。

最佳答案

您已经通过调用 thefile.readlines() 消耗了文件的所有行。 ;当您开始循环时 for one_line in thefile:没有更多的行要读取,所以循环永远不会被执行。

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

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

并迭代:
for one_line in line_list:

以下是一些包含更多信息的相关问题:

Read multiple times lines of the same file Python

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

关于python - 文件在 python try 的 else block 中有零行,除了代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61917457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com