digitalo
V2EX  ›  问与答

Python 菜鸟请教

  •  
  •   digitalo · Jun 15, 2018 · 1790 views
    This topic created in 2977 days ago, the information mentioned may be changed or developed.

    同时逐行读取两个 txt 里的内容:
    如 with open(fb,'r') as fb:
    with open(fq,'r') as fq:
    若是采用 for 循环分别读取两个文件,for 循环往往只有一层循环可用
    另一层只迭代了一次
    这种情况应该怎么解决?

    目的:实现同时读取两个 txt 内容,去请求。
    a.txt 存手机号
    b.txt 存分数

    6 replies    2018-06-16 06:22:19 +08:00
    matrix273
        1
    matrix273  
       Jun 15, 2018 via Android
    with open('a.txt') as fr_a:
    lines_a=fr_a.readlines()
    with open('b.txt) as fr_b:
    lines_b=fr_b.readlines()
    for i in range(len(lines_a)):
    print lines_a[i],lines_b[i]
    是这个意思?
    pabupa
        2
    pabupa  
       Jun 16, 2018
    不用 with 不就完了吗~
    v2gba
        3
    v2gba  
       Jun 16, 2018   ❤️ 1
    >>> with open('a', 'r') as a, open('b', 'r') as b:
    ... for ia, ib in zip(a, b):
    ... print(ia.strip(), ib.strip())
    laike9m
        4
    laike9m  
       Jun 16, 2018 via Android
    和 with 没啥关系吧,用 zip 不行么
    digitalo
        5
    digitalo  
    OP
       Jun 16, 2018
    @MrGba2z 感谢 解决了
    digitalo
        6
    digitalo  
    OP
       Jun 16, 2018
    @matrix273 对的 这样循环只有一层可以用
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5351 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 07:59 · PVG 15:59 · LAX 00:59 · JFK 03:59
    ♥ Do have faith in what you're doing.