gpt4 book ai didi

python - 无法返回从文件(.csv)读取的列表

转载 作者:太空宇宙 更新时间:2023-11-03 16:06:20 25 4
gpt4 key购买 nike

我一直在学习和练习python,期间我在程序中发现一处错误,但无法解决。我想返回从 csv 文件检索的列表。我尝试了下面的代码,它返回一个错误。

import csv

def returnTheRowsInTheFile(fileName):
READ = 'r'
listOfRows = []
try:
with open(fileName, READ) as myFile:
listOfRows = csv.reader(myFile)
return listOfRows
except FileNotFoundError:
print('The file ' + fileName + ' is not found')
except:
print('Something went wrong')
finally:
#myFile.close()
print()

def main():
fullString = returnTheRowsInTheFile('ABBREVATIONS.CSV')
for eachRow in fullString:
print(eachRow)
return

main()

错误是

Traceback (most recent call last): File "C:\Users\santo\workspace\PyProject\hello\FinalChallenge.py", line 36, in main() File "C:\Users\santo\workspace\PyProject\hello\FinalChallenge.py", line 32, in main for eachRow in fullString: ValueError: I/O operation on closed file.

最佳答案

解决此问题的简单方法是从函数返回一个列表。我知道您分配了 listOfRows = [],但是当您执行 listOfRows = csv.reader(myFile) 时,它被覆盖了。

所以,简单的解决方案是:

def returnTheRowsInTheFile(fileName):
READ = 'r'
try:
with open(fileName, READ) as myFile:
listOfRows = csv.reader(myFile)
return list(listOfRows) # convert to a list
except FileNotFoundError:
print('The file ' + fileName + ' is not found')
except:
print('Something went wrong')

您还应该阅读pep8这是 Python 的风格指南;以了解如何命名变量和函数。

关于python - 无法返回从文件(.csv)读取的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39743572/

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