简体   繁体   English

读取CSV文件导致列表索引超出范围

[英]Reading CSV file results in list index out of range

I have a csv file with numerous columns and some columns have more rows than others. 我有一个包含许多列的csv文件,有些列比其他列有更多行。 I am trying to read certain columns and extract those columns to a different csv file. 我正在尝试读取某些列,并将这些列提取到另一个csv文件中。 However, I keep getting list index out of range because the columns I'm reading are shorter than the other columns in the csv file. 但是,我不断使列表索引超出范围,因为我正在读取的列比csv文件中的其他列短。

import csv
import os
import os.path

'Open csv directory to extract data from'
path = 'S://Raw Data/VehicleData/'               

'Get file names and print number of files in the directory'
files = [f for f in os.listdir(path)]
print(files)
print(len(files))

'Start loop to scan through files in directory'
for j in range(len(files)):

'determine name of file and the output name of the file'
name = files[j]
print(name)

'path to file to open'
fpath = os.path.join(path, files[j])

    if files[j].endswith(".csv"):
        nameout = 'VehicleN3STPData' + '.csv'
        with open (fpath, 'r', newline='') as csvfile:
            testcsv = csv.reader(csvfile,delimiter=',')
            with open (nameout,'a+',newline='') as outfile:
                writer = csv.writer(outfile)
                for row in testcsv:
                    my_row = []
                    my_row.append(row[59])
                    my_row.append(row[111])
                    my_row.append(row[120])
                    print(my_row)
                    writer.writerow(my_row)
                outfile.close()    
        csvfile.close()

You need a conditional statement to check for length or you need a try & except clause depending on your intended behavior. 您需要一个条件语句来检查长度,或者需要一个try&except子句,具体取决于您的预期行为。

Here's an example of using a conditional statement that preserves the column values as blanks if they don't exist. 这是一个使用条件语句的示例,该条件语句将列值保留为空白(如果不存在)。

Instead of: 代替:

my_row.append(row[59]) 
my_row.append(row[111]) 
my_row.append(row[120])

Do: 做:

for col_num in [59, 111, 120]:
    my_row.append(row[col_num] if len(row) > col_num else '')

Thanks for your help, here is the final code that worked, removing the header with islice, using your conditional statement, and then removing the blank lines with if any(my_row) thanks!! 感谢您的帮助,这是工作的最终代码,使用条件语句删除带有islice的标题,然后删除空行,如果有的话(my_row)谢谢!

    if files[j].endswith(".csv"):
    nameout = 'VehicleN3STPData' + '.csv'
    with open (fpath, 'r', newline='') as csvfile:
        testcsv = csv.reader(csvfile,delimiter=',')
        with open (nameout,'a+',newline='') as outfile:
            writer = csv.writer(outfile)
            for row in islice(testcsv,3,None):
                    my_row = []
                    for col_num in [59,111,120]:
                        my_row.append(row[col_num] if len(row) > col_num else '')
                    if any(my_row):
                        writer.writerow(my_row)
            outfile.close()    
    csvfile.close()enter code here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM