현재 CSV 파일에 두 개의 부동 소수점 열을 읽고 각 열의 평균을 찾는 스크립트를 작성 중입니다. 내 코드가 닫힌 파일에 대한 ValueError I/O 작업을 왜 제공하는지 이해할 수 없습니다.닫힌 csv 파일에 대한 연산 ValueError, 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
고맙습니다 @jdigital 나는 두 개의 루프가 필요하다는 생각이 어디 있는지 모르겠습니다. 도움을 주셔서 감사합니다 – Matticus