【问题标题】:how to iterate lines from a text file and do something?如何从文本文件中迭代行并执行某些操作?
【发布时间】:2021-10-01 18:35:58
【问题描述】:
with open("list.txt") as f:
    lst = (f)
    print(lst)
for h in lst:
    print(lst[h])

在一个循环中,我想打开一个文件,将第一行作为 var 并使用 selenium 执行某些操作,然后再使用另一行并再次执行 selenium 操作,直到最后一行。 从晚上开始尝试只得到错误。 like 列表索引必须是整数或切片,而不是 str。

【问题讨论】:

  • @ThomasWeller 我只想在页面上粘贴第一行文件并生成。然后对其余的行执行相同的操作。
  • print(h) 代替print(lst[h]) 你会看到一行一行的得到
  • 这能回答你的问题吗? How to read a file line-by-line into a list?

标签: python python-3.x list selenium loops


【解决方案1】:

为什么不这样:

with open("list.txt") as f:
   for line in f:
     print(line)
     # do selenium stuff
     if somecondition :
        break

【讨论】:

    【解决方案2】:
    with open("list.txt", 'r') as f:
        lines = f.readlines()
    
        for line in Lines:
           # do smth here
    

    【讨论】:

      【解决方案3】:

      看起来您想读取文件 list.txt 中的数据,并希望打印出列表,其中文件 list.txt 的每一行作为 lst 的元素。你会想这样做-

      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])
      

      【讨论】:

        【解决方案4】:

        你也可以试试这样的

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-02-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-24
          • 2011-08-26
          • 2017-11-19
          相关资源
          最近更新 更多