如何并行处理来自两个不同文件的行

时间:2019-01-11 17:59:51

标签: python for-loop

我可以成功地将TZ.txt文件内容(一次一行)插入到%s所在的url行中,这是完美的。

我在TZContents.txt中保存有json格式的数据,我需要以与插入TZ.txt文件内容相同的方式将这些数据插入有效负载='{}'括号中。目前暂时还没有这样做,我觉得这个设置不正确。有什么建议吗?

我不像在TZ.txt文件中那样关心内容文件中的行。

从本质上讲,在我尝试添加有效负载参数以将我拥有的有效负载插入另一个文件中之前,代码运行良好,但到目前为止尚未成功。如果您需要更多信息,请告诉我。谢谢您的帮助。

import requests, meraki, os, json

with open('TZ.txt') as file, open ('TZContents.txt') as file2:
    array = file.readlines()
    array1 = file2.readlines()
    for line in array:
         for line2 in array1:
             line = line.rstrip("\n")
             url = 'https://dashboard.meraki.com/api/v0/networks/%s' %line
             payload = "{%s}" %line2
             headers = {'X-Cisco-Meraki-API-Key': 'API KEY','Content-Type': 'application/json'}
             response = requests.request('PUT', url, headers = headers, data = payload, allow_redirects=True, timeout = 10)
             print(response.text)

2 个答案:

答案 0 :(得分:1)

您需要像这样使用zip:

import requests

with open('TZ.txt') as file:
    tz_lines = file.readlines()

with open ('TZContents.txt') as file2:
    tz_contents = file2.readlines()

for name, contents in zip(tz_lines, tz_contents):
    url = 'https://dashboard.meraki.com/api/v0/networks/%s' % name.rstrip("\n")
    headers = {'X-Cisco-Meraki-API-Key': 'API KEY','Content-Type': 'application/json'}
    response = requests.request('PUT', url, headers=headers, data='{%s}' % contents, allow_redirects=True, timeout = 10)
    print(response.text)

这也很容易出错。如果可能的话,最好以一种不依赖于完美排列的方式生成源数据。要捕获可能的错误,您可以尝试以下操作:

if len(tz_lines) != len(tz_contents):
    raise RuntimeError("Files are not the same length!")

但是理想情况下,您只是将所有数据放在首位。将所有内容另存为JSON将是理想的选择:

[
  {"name": "the name string", "payload": {"your": "payload"}},
  "more rows"
]

然后,您可以在这些json.load(file)块中使用with。请求具有对JSON的良好支持,因此您可以像传递文件内容一样直接传递解码的JSON。

答案 1 :(得分:1)

您实际上已经很接近了,并且您显然对可以改进的代码有所了解:做得好!拥有两个文件后,您需要安排并行处理每个文件中的一行。

一种方法是:

with open('TZ.txt') as file, open ('TZContents.txt') as file2:
    for line in file1:
        line2 = file2.next()
        ...

如果文件足够小,可以像您一样读入内存,那么您还可以考虑使用zip内置函数。

>>> list(zip(['a', 'b', 'c'], [1, 2, 3]))
[('a', 1), ('b', 2), ('c', 3)]

因此您可以将其编码为:

with open('TZ.txt') as file, open ('TZContents.txt') as file2:
    for line, line2 in zip(file1, file2):
        ...

我希望我们可以同意这是很容易阅读的,并且似乎可以使代码的意图明确。

相关问题