首页 > 解决方案 > 在python中循环两个文本文件

问题描述

这是我第一次来这里,我希望得到你的帮助。我是 python 新手,我需要你的帮助

我这里有两个 .txt 文件,一个 Example file1.txt

customer1.com
customer2.com
customer3.com
customer4.com
customer5.com
customer6.com
customer7.com
customer8.com
customer9.com

文件2.txt

service1
service2
service3

我想在 file1.txt => 上循环 file2.txt,如下例所示

customer1.com/service1
customer1.com/service2  
customer1.com/service3

customer2.com/service1
customer2.com/service2  
customer2.com/service3

customer3.com/service1
customer3.com/service2  
customer3.com/service3

一直持续到 file1.txt 完成。

我还需要制作 IF 语句,例如假设客户编号 3 的服务编号为 2(我的意思是找到文件)

customer3.com/service2 [找到服务]

我需要customer3的循环停止寻找服务并将输出(customer3.com/service2)保存在一个名为file3.txt的新文件中,并且循环与其他客户一起继续,每个客户都找到了服务,输出保存在文件3.txt

我希望你明白我的意思。谢谢。

标签: python

解决方案


您可以使用itertools.product从每个文件中获取行的笛卡尔积来获取每个 URL 组合:

from itertools import product

with open("file1.txt") as f1, open("file2.txt") as f2, open(
    "file3.txt", mode="w"
) as out:
    for x, y in product(f1, f2):
        out.write("%s/%s\n" % (x.strip(), y.strip()))

文件 3.txt

customer1.com/service1
customer1.com/service2
customer1.com/service3
customer2.com/service1
customer2.com/service2
customer2.com/service3
customer3.com/service1
customer3.com/service2
...

推荐阅读