私は多数の列を持つcsvファイルを持っていて、いくつかの列は他の列より多くの行を持っています。私は特定の列を読み込み、それらの列を別のcsvファイルに抽出しようとしています。しかし、私が読んでいる列は、csvファイルの他の列よりも短いため、リストの索引が範囲外になっています。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()