python与csv的问题

时间:2016-08-13 21:32:27

标签: python csv pycharm

我刚刚开始学习python,同时学习数据分析的udacity课程,并且在pyCharm中遇到了我的代码问题。在前言中,代码在udacity shell中使用时工作,文件位置更改为udacity网站的指示位置。下面是代码和我得到的2个错误。我知道C ++并认为python可以轻而易举地学习,但除了编码本身,我倾向于得到以前从未遇到的这些类型的错误。如果有任何经验法则如何避免这种情况,我们将不胜感激。

import csv

daily_engagements = []
project_submissions = []

with open(r'C:\Users\austi\Downloads\daily_engagement.csv', 'rt') as f:
    reader = csv.DictReader(f)
    daily_engagement = list(reader)
print(project_submissions[5])

with open(r'C:\Users\austi\Downloads\project_submissions.csv', 'rt') as g:
    reader1 = csv.DictReader(g)
    project_submissions = list(reader)
print(daily_engagement[17])

错误1

   C:\Users\austi\AppData\Local\Programs\Python\Python35-32\python.exe  
           C:/Users/austi/PycharmProjects/untitled2/p2prac.py
Traceback (most recent call last):
  File "C:/Users/austi/PycharmProjects/untitled2/p2prac.py", line 15, in    <module>
    project_submissions = list(reader)
  File "C:\Users\austi\AppData\Local\Programs\Python\Python35- 32\lib\csv.py", line 110, in __next__
    row = next(self.reader)
ValueError: I/O operation on closed file.

Process finished with exit code 1

错误2

C:\Users\austi\AppData\Local\Programs\Python\Python35-32\python.exe   
C:/Users/austi/PycharmProjects/untitled2/p2prac.py
Traceback (most recent call last):
  File "C:/Users/austi/PycharmProjects/untitled2/p2prac.py", line 10, in  <module>
    print(project_submissions[5])
IndexError: list index out of range

Process finished with exit code 1

1 个答案:

答案 0 :(得分:1)

我会在内联评论中注意您的错误。基本上,您似乎无法跟踪对象及其名称。

import csv

daily_engagements = [] # this is never used
project_submissions = [] # you never add anything to this list

with open(r'C:\Users\austi\Downloads\daily_engagement.csv', 'rt') as f:
    reader = csv.DictReader(f)
    daily_engagement = list(reader)
print(project_submissions[5]) # you've never added to this list, so it has no element 5... did you mean to use daily_engagement?

with open(r'C:\Users\austi\Downloads\project_submissions.csv', 'rt') as g:
    reader1 = csv.DictReader(g)
    project_submissions = list(reader) # you are using reader, which was closed already, rather than reader1
print(daily_engagement[17])

这是一个清理版本。我没有您的文件,我也不知道您要打印哪些数据,但这可能是您想要的,我可以确定:

import csv

with open(r'C:\Users\austi\Downloads\daily_engagement.csv') as f:
    reader = csv.DictReader(f)
    daily_engagement = list(reader)
print(daily_engagement[5])

with open(r'C:\Users\austi\Downloads\project_submissions.csv') as g:
    reader = csv.DictReader(g)
    project_submissions = list(reader)
print(project_submissions[17])