简体   繁体   English

Python 打开并读取多个 url txt 文件

[英]Python open and read multiple url txt files

I have this code below and only the contents of file links.txt are being read,,,, the second file (links2.txt) is treated as non-existent by python... how do I read the urls in the 2 files...我在下面有这段代码,只有文件links.txt的内容被读取,第二个文件(links2.txt)被python视为不存在......我如何读取2个文件中的url ...

for i in range(50):
with open("links.txt") as f1, open("links2.txt") as f2:
    urls1 = f1.readlines()
    urls2 = f2.readlines()
    random_urls1 = random.sample(urls1, 5)
    random_urls2 = random.sample(urls2, 5)
    for url in random_urls1:
        driver.get(url.strip())
        time.sleep(2)
        try:
            cors1()
        except:
            continue

    for url in random_urls2:
        driver.get(url.strip())
        time.sleep(2)
        try:
            cors2()
        except:
            continue

What am I missing in the code?我在代码中遗漏了什么? Thanks谢谢

I'm not sure this is producing the error that you think it is.我不确定这是否会产生您认为的错误。 I took most of your code and replaced most of the for loop with a print(url) and populated my own files with mostly random words.我拿走了你的大部分代码,并用print(url)替换了大部分 for 循环,并用大部分随机单词填充了我自己的文件。 I'm able to see values from both files coming in. So is it possible you're seeing the same values in both files but thinking only one is read?我能够看到来自两个文件的值。那么您是否有可能在两个文件中看到相同的值但认为只读取了一个? Can you verify any of the records as coming from one file vs the other, say by adding the file name to a print(url) ?您可以通过将文件名添加到print(url)来验证任何记录是否来自一个文件与另一个文件?

import random

with open("links.txt") as f1, open("links2.txt") as f2:
    urls1 = f1.readlines()
    urls2 = f2.readlines()
    random_urls1 = random.sample(urls1, 5)
    random_urls2 = random.sample(urls2, 5)
    for url in random_urls1:
        print(url)

    for url in random_urls2:
        print(url)

Below are the results I produced along with the source file values I used.下面是我生成的结果以及我使用的源文件值。 Not urls but I wanted to simplify to see if I could reproduce the issue.不是网址,但我想简化以查看是否可以重现该问题。

results

tony
hulk
taken
stark
christian
py
hahaha
hard
ulo
welp
links.txt

blah
taken
liam
neeson
bale
christian
tony
stark
avenger
hulk
links2.txt

blah2
hard
soft
lambdra
hello
py
hahaha
welp
ulo
yolo
text

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

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