0
with open("list.txt") as f:
    lst = (f)
    print(lst)
for h in lst:
    print(lst[h])

In a loop i want to open a file take 1st line as a var and do something with selenium and then take another line and do the selenium stuff again until last line. trying since evening only getting errors. like list indices must be integers or slices, not str.

Deepak
  • 11
  • 1
  • @ThomasWeller i just want to take 1st line of file paste on a page and generate. and then do the same for rest of the lines. – Deepak Jul 25 '21 at 14:23
  • Do a `print(h)` instead of `print(lst[h])` and you'll see that you get a single line one by one – Thomas Weller Jul 25 '21 at 14:25
  • 2
    Does this answer your question? [How to read a file line-by-line into a list?](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list) – Tomerikoo Jul 25 '21 at 18:51

4 Answers4

0

Why not this :

with open("list.txt") as f:
   for line in f:
     print(line)
     # do selenium stuff
     if somecondition :
        break
cruisepandey
  • 28,520
  • 6
  • 20
  • 38
0
with open("list.txt", 'r') as f:
    lines = f.readlines()

    for line in Lines:
       # do smth here
4d61726b
  • 427
  • 5
  • 26
0

Looks like you want to read the data in the file list.txt and want to print out the list with each line of file list.txt as an element of lst. You would want to do that like-

lst = []
with open("list.txt") as f:
    for new in f:
        if new != '\n':
            addIt = new[:-1].split(',')
            lst.append(addIt)

for h in lst:
        print(lst[h])
iamakhilverma
  • 564
  • 3
  • 9
0

You can try something like this as well

lst = open("list.txt").read().split('\n')
for each in lst:
    print(each)
codewithawais
  • 551
  • 1
  • 6
  • 25