I would like to print (stdout) the first two lines of a csv file:
#!/usr/bin/env python
import csv
afile = open('<directory>/*.csv', 'r+')
csvReader1 = csv.reader(afile)
for row in csvReader1:
print row[0]
print row[1]
however, my output using this code print the first two columns.
Any suggestions?
You want to print a row, but your code asks to print the first and second members of each row
Since you want to print the whole row - you can simply print it, and in addition, only read the first two
#!/usr/bin/env python
import csv
afile = open('<directory>/*.csv', 'r+')
csvReader1 = csv.reader(afile)
for i in range(2):
print csvReader1.next()
Generally, you can limit iterators with the itertools.islice
function:
import itertools
for row in itertools.islice(csvReader1, 2):
print row
Or by a creative use of zip()
:
for line_number, row in zip(range(2), csvReader1):
print row
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With