【发布时间】:2018-05-15 04:13:18
【问题描述】:
我目前正在编写一个脚本来读取 CSV 文件中的两列浮点数并找到每列的平均值。我不明白为什么我的代码在关闭文件上给我一个 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()
【问题讨论】:
-
您不需要关闭文件并重新打开它。您可以在一个循环中访问所有列
-
谢谢@jdigital 我不知道我从哪里得到需要两个循环的想法。感谢您的帮助
标签: python python-3.x csv valueerror