kainy kainy -3 years ago 82
Python Question

Extra row appended when adding columns to CSV file

I am reading in CSV files, removing the header, and appending two columns of data. Everything is working great, aside from an extra row being added at the end. For example, if I have the following input file:

headerA | headerB | headerC
a | b | c
d | e | f

I want the output file to look like:

a | b | c | g | h
d | e | f | g | h

But it's coming out like:

a | b | c | g | h
d | e | f | g | h
g | h

I cannot for the life of me figure out why this is the case. If anyone has a solution, it would be greatly appreciated. Here's my code:

for fileName in os.listdir(inPath):
if fileName.endswith('.csv'):
with open(inPath + fileName, 'rb') as csvin:
reader = csv.reader(csvin, delimiter=',')
i = reader.next()
with open(outPath + 'wrng_' + fileName, 'wb') as csvout:
writer = csv.writer(csvout, delimiter=',')
for row in reader:
j = fileName.split("_")[1].replace(".csv","")
row.append(j[2:-7] + '-' + j[4:-5] + '-' + j[:2] + ' ' + j[7:-2] + ':' + j[9:] + ':00')
row.append(i[1].split(" ")[2][:-1])

Answer Source

(Summarizing from the comments) It looks like the problem you are having could be caused by an empty row at the end of the file. You can check to see if the row is empty within your for loop.

for row in reader:
    if row:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download