Here is my code so far:
import csv
reader = csv.reader(open('new_file.txt','r'),delimiter=' ')
row1 = reader[0]
row2 = reader[1]
row3 = reader[2]
Here is my new_file.txt
:
this is row one
this is row two
this is row three
When I run It i have the following error:
Traceback (most recent call last):
File "/home/me/Documents/folder/file.py", line 211, in <module>
row1 = reader[0]
TypeError: '_csv.reader' object has no attribute '__getitem__'
How can I fix that?
Thanks.
A csv.reader()
object is not a sequence. You cannot access rows by index.
You'd have to 'slurp' the whole iterable into a list for that:
rows = list(reader)
row1 = rows[0]
row2 = rows[1]
row3 = rows[2]
This is generally not a good idea. You can instead ask for the next value from the iterator with the next()
function:
reader = csv.reader(open('new_file.txt','r'),delimiter=' ')
row1 = next(reader)
row2 = next(reader)
row3 = next(reader)
You can loop the reader
and then access the row
elements:
import csv
reader = csv.reader(open('new_file.txt','r'),delimiter=' ')
for row in reader:
row1 = row[0]
row2 = row[1]
row3 = row[3]
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