简体   繁体   English

如何从文本文件中迭代行并执行某些操作?

[英]how to iterate lines from a text file and do something?

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.在一个循环中,我想打开一个文件,将第一行作为 var 并用 selenium 做一些事情,然后再用另一行做 selenium 的东西,直到最后一行。 trying since evening only getting errors.从晚上开始尝试只会出错。 like list indices must be integers or slices, not str.像列表索引必须是整数或切片,而不是 str。

Why not this :为什么不是这个:

with open("list.txt") as f:
   for line in f:
     print(line)
     # do selenium stuff
     if somecondition :
        break
with open("list.txt", 'r') as f:
    lines = f.readlines()

    for line in Lines:
       # do smth here

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.看起来你想读取文件list.txt 中的数据,想打印出list.txt 文件的每一行作为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])

You can try something like this as well你也可以尝试这样的事情

lst = open("list.txt").read().split('\n')
for each in lst:
    print(each)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM