0

I am sure there is a better way or writing this python function:

end_points = list(range(100))
filepath = 'something.csv'
with open(filepath) as fp:
    cnt = 0
    for line in fp:
        end_points[cnt]=[x.strip() for x in line.split(',')]
        cnt += 1

It works but it is not elegant. Is there a way of automatically refers to the current number of iteration in the for loop?

Sayse
  • 42,633
  • 14
  • 77
  • 146
Leos313
  • 5,152
  • 6
  • 40
  • 69

2 Answers2

4

You can also use the enumerate function:

for iteration_no, line in enumerate(fp):
    print(iteration_no)
    end_points[iteration_no]=[x.strip() for x in line.split(',')]

If you are more generally interested in seeing the progress of your loop you should alternatively have a look at the TQDM package which dynamically prints the progress of your loop.

https://github.com/tqdm/tqdm

Matthias
  • 12,873
  • 6
  • 42
  • 48
Dominique Paul
  • 1,623
  • 2
  • 18
  • 31
1

Not sure of being elegant but is shorter,

>>> with open("something.csv") as f:
...     result = [list(map(str.strip,x.split(','))) for x in f]
...     print(result)
abhilb
  • 5,639
  • 2
  • 20
  • 26