【问题标题】:Reading data from a CSV file in Python在 Python 中从 CSV 文件中读取数据
【发布时间】:2015-01-10 06:27:38
【问题描述】:

我正在从包含以下数据的 CSV 文件 (xyz.CSV) 中读取数据:

col1,col2,col3,col4
name1,empId1,241682-27638-USD-CIGGNT ,1
name2,empId2,241682-27638-USD-OCGGINT ,1
name3,empId3,241942-37190-USD-GGDIV ,2
name4,empId4,241942-37190-USD-CHYOF ,1
name5,empId5,241942-37190-USD-EQPL ,1
name6,empId6,241942-37190-USD-INT ,1
name7,empId7,242066-15343-USD-CYJOF ,3
name8,empId8,242066-15343-USD-CYJOF ,3
name9,empId9,242066-15343-USD-CYJOF ,3
name10,empId10,241942-37190-USD-GGDIV ,2

当我使用循环对其进行迭代时,我可以通过以下代码逐行打印数据,并且仅打印 column1 数据。

file=open( path +"xyz.CSV", "r")
reader = csv.reader(file)
for line in reader:
    t=line[0]
    print t

通过上面的代码我只能得到第一列。

如果我尝试打印 line[1] 或 line[2] 它会给我以下错误。

    file=open( path +"xyz.CSV", "r")
    reader = csv.reader(file)
    for line in reader:
        t=line[1],[2]
        print t

t=line[1],line[2]
IndexError: list index out of range

请建议打印 column2 或 column3 的数据。

【问题讨论】:

标签: python csv


【解决方案1】:

希望能解决问题

import csv
file=open( "xyz.CSV", "r")
reader = csv.reader(file)
for line in reader:
    t=line[0]+","+line[1]
    print (t)

【讨论】:

  • 不,它给出与 IndexError 相同的错误:列表索引超出范围。
  • 奇怪!它在我的机器上运行良好。你到底给 t 分配了什么?
【解决方案2】:

您的第一行只有一列,因此该过程失败并且不会继续。要解决,只需跳过第一行

>>> with open( path, "r") as file:
...     reader = csv.reader(file)
...     for idx,line in enumerate(reader):
...         if idx>0:
...             t=line[1],line[2]
...             print t
... 
('empId1', '241682-27638-USD-CIGGNT ')
('empId2', '241682-27638-USD-OCGGINT ')
('empId3', '241942-37190-USD-GGDIV ')
('empId4', '241942-37190-USD-CHYOF ')
('empId5', '241942-37190-USD-EQPL ')
('empId6', '241942-37190-USD-INT ')
('empId7', '242066-15343-USD-CYJOF ')
('empId8', '242066-15343-USD-CYJOF ')
('empId9', '242066-15343-USD-CYJOF ')
('empId10', '241942-37190-USD-GGDIV ')

【讨论】:

    【解决方案3】:
    import csv
    csv_file=open("xyz.csv", "r")
    reader = csv.reader(csv_file)
    
    for row in reader:
        print(" ".join(row[:2]))
    
    Output :- 
    col1 col2
    name1 empId1
    name2 empId2
    name3 empId3
    name4 empId4
    name5 empId5
    name6 empId6
    name7 empId7
    name8 empId8
    name9 empId9
    name10 empId10
    

    只需将值作为切片放入行中。下面是打印第 2 列和第 3 列的代码。

    import csv
    csv_file=open("xyz.csv", "r")
    reader = csv.reader(csv_file)
    
    for row in reader:
        print(" ".join(row[1:3]))
    
    output:
    col2 col3
    empId1 241682-27638-USD-CIGGNT 
    empId2 241682-27638-USD-OCGGINT 
    empId3 241942-37190-USD-GGDIV 
    empId4 241942-37190-USD-CHYOF 
    empId5 241942-37190-USD-EQPL 
    empId6 241942-37190-USD-INT 
    empId7 242066-15343-USD-CYJOF 
    empId8 242066-15343-USD-CYJOF 
    empId9 242066-15343-USD-CYJOF 
    empId10 241942-37190-USD-GGDIV 
    

    【讨论】:

      【解决方案4】:

      第二列和第三列是这样的:

      import csv
      
      path = 'c:\\temp\\'
      
      file=open( path +"xyz.CSV", "r")
      reader = csv.reader(file)
      for line in reader:
          t=line[1],line[2]
          print(t)
      

      结果如下:

      ('col2', 'col3')
      ('empId1', '241682-27638-USD-CIGGNT ')
      ('empId2', '241682-27638-USD-OCGGINT ')
      ('empId3', '241942-37190-USD-GGDIV ')
      ('empId4', '241942-37190-USD-CHYOF ')
      ('empId5', '241942-37190-USD-EQPL ')
      ('empId6', '241942-37190-USD-INT ')
      ('empId7', '242066-15343-USD-CYJOF ')
      ('empId8', '242066-15343-USD-CYJOF ')
      ('empId9', '242066-15343-USD-CYJOF ')
      ('empId10', '241942-37190-USD-GGDIV ')
      

      【讨论】:

        【解决方案5】:

        要在 Python 中读取和写入文本文件,可以使用以下语法:

        f = open('helloworld.txt','r')
        message = f.read()
        print(message)
        f.close()
        
        
        f = open('helloworld.txt','w')
        f.write('hello world')
        f.close()
        

        要读取 CSV 文件,请执行以下代码: 结果 = []enter code here 使用 open("C:/Users/Prateek/Desktop/TA Project/data1.csv") 作为输入文件: 对于输入文件中的行: results.append(line.strip().split(','))

        【讨论】:

          【解决方案6】:

          有一个简单的方法可以查看更多信息: Python CSV Docs

          with open(filename, 'r') as csvfile:
                  spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
                  for row in spamreader:
                      data.append(row)
          

          【讨论】:

            【解决方案7】:

            虽然这是一个很老的问题,但只想分享我的建议。发现在数据框中使用 pandas 读取 csv 并访问数据更容易。

            import pandas
            
            df = pandas.read_csv('<path/to/your/csv/file>')
            
            print(df)
            #OUTPUT
            #     col1     col2                       col3  col4
            #0   name1   empId1   241682-27638-USD-CIGGNT      1
            #1   name2   empId2  241682-27638-USD-OCGGINT      1
            #2   name3   empId3    241942-37190-USD-GGDIV      2
            #3   name4   empId4    241942-37190-USD-CHYOF      1
            #4   name5   empId5     241942-37190-USD-EQPL      1
            #5   name6   empId6      241942-37190-USD-INT      1
            #6   name7   empId7    242066-15343-USD-CYJOF      3
            #7   name8   empId8    242066-15343-USD-CYJOF      3
            #8   name9   empId9    242066-15343-USD-CYJOF      3
            #9  name10  empId10    241942-37190-USD-GGDIV      2
            
            #you can access any column using
            
            df['col2']
            #OUTPUT
            #0     empId1
            #1     empId2
            #2     empId3
            #3     empId4
            #4     empId5
            #5     empId6
            #6     empId7
            #7     empId8
            #8     empId9
            #9    empId10
            #Name: col2, dtype: object
            
            
            #Or print a specific value using
            df['col2'][0]
            

            更新:我主要在我的项目中使用 Pandas,所以发现使用它来读取 csv 也更容易。还有其他专用库可用于读取 CSV(创建自己的 CSV 阅读器也应该是几行代码)。

            【讨论】:

            • 此类任务有一个标准库 (csv)。 Pandas 是 46MB 的原生库依赖项。如果您在项目的其他部分使用它,可以,但仅针对此任务读取 CSV 是一种非常糟糕的做法
            • @4lberto 我在项目中使用了 pandas,所以并没有真正探索其他专用库。根据您的建议更新答案。
            【解决方案8】:

            你也可以在不导入pandas和csv的情况下读取csv数据

            with open('testdata.csv', 'r') as f:
                results = []
                for line in f:
                        words = line.split(',')
                        results.append((words[0], words[1:]))
                print (results)
            

            【讨论】:

              【解决方案9】:

              加载预处理后的 CSV 数据

              data_preprocessed = pd.read_csv('file_name.csv')
              

              【讨论】:

              • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
              猜你喜欢
              • 1970-01-01
              • 2018-01-08
              • 2014-01-07
              • 2019-09-17
              • 1970-01-01
              • 2021-02-06
              • 2013-06-23
              相关资源
              最近更新 更多