I have a csv file with numerous columns and some columns have more rows than others. I am trying to read certain columns and extract those columns to a different csv file. 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.
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()