i am want to read data from the csv that i wrote using python csv module but apart from filed names and row count i am unable to read rest of the data
Peter Otten
__peter__ at web.de
Wed Apr 15 04:28:04 EDT 2020
sjeik_appie at hotmail.com wrote:
> On 12 Apr 2020 12:30, Peter Otten <__peter__ at web.de> wrote:
>
> Rahul Gupta wrote:
>
> >for line in enumerate(csv_reader):
> >print(line[csv_reader.fieldnames[1]])
>
> enumerate() generates (index, line) tuples that you need to unpack:
>
> for index, line in enumerate(csv_reader):
> print(line[csv_reader.fieldnames[1]])
>
> ==》 Shouldn't that be, e.g:
> print( line[csv_reader.fieldnames[1].index()] )
No. Remember that the OP used a DictReader. If you want to clean up the
original code you can use a csv.reader
csv_reader = csv.reader(csv_file)
fieldnames = next(csv_reader)
for row in csv_reader:
print(row[1])
but my assumption was that
> print(line[csv_reader.fieldnames[1]])
wasn't the final code, only something to get things working.
> Or maybe:
> cols = csv_reader.fieldnames
> print( [[val for val, col in zip(record, cols) if col in ['somecol']]
> for record in csv_reader])
> ?
This is ugly and complex. It can be simplified to
num_rows = sum(1 for _ in csv_reader)
print([["somecol"]] * num_rows)
Why would you want to do this?
More information about the Python-list
mailing list