gpt4 book ai didi

python - 对关闭的 csv 文件进行操作 ValueError,Python 代码

转载 作者:行者123 更新时间:2023-12-01 02:24:01 25 4
gpt4 key购买 nike

我目前正在编写一个脚本来读取 CSV 文件中的两列 float 并查找每列的平均值。我不明白为什么我的代码在关闭的文件上给我一个 ValueError I/O 操作。

我的代码有两个打开语句,因为据我了解,您必须关闭文件并重新打开它,然后才能添加并查找第二列的平均值。

我的代码如下,我很感谢我能得到的任何反馈,这对我来说没有意义。谢谢。

语言:Python 3.6

def main():
import csv

file = input("What is the name of the file, dont forget the .csv: ")
INFILE = open(file,"r")
totalCol1 = 0
countCol1 = 0
totalCol2 = 0
countCol2 = 0
read = csv.reader(INFILE,lineterminator=",")

# Loop through column 1
for row in read:
totalCol1 += float(row[0])
countCol1 += 1
averageCol1 = totalCol1 / countCol1
INFILE.close()

INFILE = open(file,"r")
for row in read:
totalCol2 += float(row[1])
countCol2 += 1
averageCol2 = totalCol2 / countCol2

print('Average for Column One:%5.2f' % averageCol1)
print('Average for Column Two:%5.2f' % averageCol2)
INFILE.close()

main()

最佳答案

我怀疑发生的情况是您将 INFILE 的实例传递给 csv.reader,然后该实例关闭。因此,当您再次打开文件时,您需要将该新实例传递给 csv.reader。

话虽这么说,您可以在第一个循环中完成所有这些操作,而无需关闭并重新打开文件:

for row in read:
totalCol1 += float(row[0])
countCol1 += 1

totalCol2 += float(row[1])
countCol2 += 1

averageCol1 = totalCol1 / countCol1
averageCol2 = totalCol2 / countCol2

或者你可以只使用 pandas read_csv读取 csv,然后使用 pandas mean 计算平均值并避免循环(在 Python 中这是值得努力的)。

关于python - 对关闭的 csv 文件进行操作 ValueError,Python 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47586900/

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