python - 在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
我希望你明白我的意思。谢谢。
解决方案
您可以使用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
...
推荐阅读
- python - Pandas:如何仅删除列末尾的最后一个连字符
- google-forms - 如何根据其他用户过去的回复使 Google 表单自动填充?
- c - 我知道一个地址,但我应该如何判断在哪个部分?使用C的全局区域或堆区域或堆栈区域
- json - 如何解决“手势 RangeError(索引)捕获的异常:无效值:有效值范围为空:0”
- c++ - 什么会使多边形算法中的点仅在正向和反向运行时才能正常工作?
- php - PHP:如何使用键->值对每两个分隔符将一个字符串分解为一个数组
- kubernetes - 将 GKE 集群拆除为“全新”状态而不删除它?
- scala - Spark——自定义reduce函数保存到磁盘然后上传到s3
- javascript - XMLHttpRequest 返回事件对象而不是实际数据
- fortran - Fortran 将未知大小的文件读入数组