如何处理p中两个不同文件的行

2024-05-23 14:31:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以成功地插入TZ.txt文件将文件内容(一次一行)放入url行中%s所在的位置,这样做非常有效。你知道吗

我有json格式的数据TZContents.txt文件我需要以TZ.txt文件正在插入文件内容。它目前没有这样做,我觉得这是不正确的设置。有什么建议吗?你知道吗

我不关心内容文件中的剥离行,就像我对TZ.txt文件文件。你知道吗

基本上,代码工作得很好,直到我尝试添加一个payload参数以将有效负载插入到另一个文件中,但到目前为止还没有成功。如果你需要更多的信息,请告诉我。谢谢你的帮助。你知道吗

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)

Tags: 文件txtjsonurl内容aslineopen
2条回答

事实上,您已经非常接近了,而且您显然对可以改进的代码很敏感:做得好!一旦有了这两个文件,就需要安排并行处理每个文件中的一行。你知道吗

一种方法是:

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):
        ...

我希望我们可以同意,这是相当可读性,似乎使代码的意图明确。你知道吗

你需要像这样使用拉链:

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"
]

然后可以在这些with块中使用json.load(file)。而且请求对JSON有很好的支持,所以您可以像传递文件内容一样直接传递解码后的JSON。你知道吗

相关问题 更多 >