【问题标题】:Python 3 - Reading line by line from a textfile and doing action for each linePython 3 - 从文本文件中逐行读取并为每一行执行操作
【发布时间】:2013-06-08 23:30:50
【问题描述】:

我需要做这样的事情:

  • 登录网站。
  • 对特定 URL 执行操作。
  • 操作后,转到另一个 URL(仍在站点中)。

到目前为止,这是我所做的。

if loginAccount(user, pass, url) == 1:
    if someActionChecking(url) == 1:
        None
    else:
        print ("[INFO]blablabla")
        actionNow(url, actionProcess)

    if someActionChecking(url2) == 1:
        None
    else:
        print ("[INFO]blablabla")
        actionNow(url2, actionProcess)

    if someActionChecking(url3) == 1:
        None
    else:
        print ("[INFO]blablabla")
        actionNow(url3, actionProcess)
else:
    print ("Login failed.")

现在是问题

我想通过从包含 url1, url2, url3 的文本文件中获取 url 来缩短代码并使我的生活更轻松(例如),读取存储在那里的 URL 行行,然后每行循环 actionNow() 函数。所以它会是这样的:

if loginAccount(user, pass, url) == 1:
    if someActionChecking(url) == 1:
        None
    else:
        #I need to loop this process below!!
        print ("[INFO]blablabla")
        actionNow(url, actionProcess)
else:
    print ("Login failed.")

有什么解决方法吗?我现在已经搜索了几天,我看到的只是 strip() 技术,但我无法真正理解它是如何工作的。

希望有人可以指导我,

【问题讨论】:

    标签: python string text python-3.x text-parsing


    【解决方案1】:
    urlFile = "path/to/file"
    urls = open(urlFile).readLines()
    
    for url in urls:
      doAction(url)
    

    或者你可以把它全部放在url文件读取循环中;

    with open(urlFile) as f:
      for line in f:
        doAction(line)
    

    【讨论】:

    • @will 在with open(...) 选项中,您可能指的是doAction(line)(或者for url in f:
    • @twalberg 所以我做到了!我正在竞相找出答案!
    猜你喜欢
    • 2015-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多