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
sjeik_appie at hotmail.com
sjeik_appie at hotmail.com
Wed Apr 15 18:04:58 EDT 2020
On 15 Apr 2020 10:28, Peter Otten <__peter__ at web.de> wrote:
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 this?
===》 I thought the OP wanted to take a subset of the columns in his data.
In my example I intended to select one column, but with code that cpuld
easily be extended to a selection of multiple columns. Call it "pruning"
of the lists of lists
More information about the Python-list
mailing list