错误按摩"ValueError: I/O operation on closed file"我不能将"r"更改为'w'但仍然不起作用


with open('/Users/harryhou/Desktop/project 830/ass 2/supermarket_sales.csv', 'r') as SalesList:
for row in SalesList:
print(SalesList.readline())
for row in SalesList:
print(row)
##Write a function to receive the Supermarket Sales list (that you created in the previous question) and return the total sales (the sum of column Total) of the branches as a dictionary
##The returned information should look like (the numbers given below may not be correct):
##{"A": 123456.123, "B": 234567.567, "C": 345678.9987}
def totalSales(SalesList):
dict2 ={'A':0, 'B':0,'C':0}
for sale in SalesList:
dict2[sale[1]] += sale[9]
return dict2
print(totalSales(SalesList))
print(totalSales(SalesList))

尽管你的问题不是很清楚,但我认为我看到了你的问题。

您可以通过以下几行打开并使用代码顶部的文件句柄:

with open('/Users/harryhou/Desktop/project 830/ass 2/supermarket_sales.csv', 'r') as SalesList:
for row in SalesList:
...

一旦with块完成,则关闭该文件。这就是使用with的全部原因。它确保在with中的块执行完毕后关闭文件。您永远不应该在与with关联的代码块之外使用与with语句(本例中为SalesList(关联的文件句柄。

我猜错误发生在代码中稍后执行的这两行中的第一行:

for sale in SalesList:
dict2[sale[1]] += sale[9]

你得到这个错误的原因正是错误消息说。。。您正试图对已关闭的文件句柄进行操作。SalesList用于表示由with语句打开的文件。但该文件已被关闭。您不应该将SalesList用于with代码块之外的任何内容。

相关内容

最新更新