1

Task: Use python to parse a CSV file and output the contents of a column into a text file.

Input file (in.csv):

one,two,three  
four,five,six  

Python script:

#!/usr/bin/env python

import csv

inputFile = open('in.csv', 'r')
inputReader = csv.reader(inputFile)

outputFile = open('out.txt', 'w')
outputWriter = csv.writer(outputFile)

for row in inputReader:
        text = row[2]
        # write column 3 to file
        outputWriter.writerow(text)

outputFile.close()
inputFile.close()

Expected output

three
six

Actual output

t,h,r,e,e
s,i,x

Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
mikey
  • 115
  • 8
  • 1
    Does this answer your question? [Why does csvwriter.writerow() put a comma after each character?](https://stackoverflow.com/questions/1816880/why-does-csvwriter-writerow-put-a-comma-after-each-character) – Pranav Hosangadi Feb 19 '21 at 14:56
  • Welcome to Stack Overflow! Please take the [tour], and read [ask], [what's on-topic here](/help/on-topic) and the [question checklist](//meta.stackoverflow.com/q/260648/843953). [Asking on Stack Overflow is not a substitute for doing your own research.](//meta.stackoverflow.com/a/261593/843953) – Pranav Hosangadi Feb 19 '21 at 14:59

1 Answers1

0

The csvwriter.writerow() method expects a list. As such, it uses the string in text in a list context; i.e. it uses text as a list of characters, one for each column:

#!/usr/bin/env python

import csv

inputFile = open(name, 'r')
inputReader = csv.reader(inputFile)

outputFile = open('onetwothree.txt', 'w')
outputWriter = csv.writer(outputFile)

for row in inputReader:
        text = row[2]
        # write column 3 to file
        outputWriter.writerow([text])

outputFile.close()
inputFile.close()
VirtualScooter
  • 1,792
  • 3
  • 18
  • 28