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
  • 41,425
  • 14
  • 72
  • 139
Leos313
  • 4,458
  • 5
  • 31
  • 65

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
  • 11,699
  • 5
  • 39
  • 45
Dominique Paul
  • 1,366
  • 1
  • 17
  • 30
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,406
  • 2
  • 18
  • 26