1

I am able to get the content from an csv file:

import csv

with open("C:/Users/user/Desktop/tst/test.csv") as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=';')
    next(csv_reader)

    for line in csv_reader:
        print(line[0])

that get my first (0) line. So far so good, but the output is now:

  1. a
  2. b
  3. c

So how do i get those a, b and c? I tried to add them to a list, that wont work at all

Example: We have a Path,Name -- under the path are 3 file paths written. I can acess those paths with: the code above. So i am getting three paths among themselves How to get the first path?

enter image description here I need the testpath1 only, but I am getting everypath with my code

solarc
  • 5,638
  • 2
  • 40
  • 51

2 Answers2

0

Have you tried using Pandas to read the csv and explore with it.

mohsinali
  • 286
  • 1
  • 9
0

You can accumulate the results in a list like this:

my_list = []
for line in csv_reader:
    my_list.append(line[0])

And then use it like this:

for item in my_list:
    do_something(item)

However, you can already do that from the start and skip the extra list:

for line in csv_reader:
    do_something(line[0])

Edit:

If you need only the first item you can use next to grab the first line (like you are already using next to skip over the header probably):

next(csv_reader) # here you are pulling the first line without using it

line = next(csv_reader)
print(line) # this gives you the second line: a

line2 = next(csv_reader)
print(line2) # b
print(next(csv_reader)) # c
next(csv_reader) # if you call it after the file is finished you'll get a StopIteration exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
solarc
  • 5,638
  • 2
  • 40
  • 51
  • Same problem: I am getting more output. So my list contain a,b,c but how to access only the a? – LittleDuck19 Jan 28 '20 at 17:39
  • You access the a the first run of the loop. Do you only want to access the a and not the b and c? – solarc Jan 28 '20 at 17:41
  • See my edit in the question, should be clear now :) – LittleDuck19 Jan 28 '20 at 17:45
  • Thanks that fixed my problem, how to get rid of that error? I tried sth like: row_count = sum(1 for row in csv_reader) for the number of rows in csv file. I have to get this into a for loop right? – LittleDuck19 Jan 30 '20 at 15:28
  • You can ignore the error using a try: ... except: pass block, see https://stackoverflow.com/q/730764/154762 – solarc Jan 30 '20 at 16:57
  • If you need the number of rows you can probably use `len(csv_reader)` and then `csv_file.seek(0)` to reset it back to the start. – solarc Jan 30 '20 at 17:00
  • Hey, I hope u can finally help me bc I am stupid. I have a very long code which using the next(csv_reader) part. After this code, I need the next row, so If all this finshed, I need to restart the whole code, BUT add next(csv_reader) at the top, you know what I mean? – LittleDuck19 Jan 30 '20 at 17:19