简体   繁体   English

如何在 txt 文件 python 的每一行之后添加 \n

[英]How to add \n after every line in a txt file python

import requests
import time

req = requests.session()
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
a = open("codes.txt", "r").readlines()
param={
      "ID":a
}

source = req.post("http://www.example.com/api/", data=param, headers=headers)
if "valid" in source.text:
    print(source.text)
else:
     print(source.text)

So i have a file called codes.txt and i have some id's in the file.所以我有一个名为codes.txt的文件,我在文件中有一些ID。

1234
12345
12346

And after that i send a request to verify if the id is valid or not.之后我发送一个请求来验证 id 是否有效。

So when im checking and adding multiple ids in that txt file it becomes 1 id 123412345123456因此,当我在该 txt 文件中检查并添加多个 id 时,它变为 1 id 123412345123456

How i can add a \n to every line and make a request for every id.我如何在每一行添加一个 \n 并为每个 ID 发出请求。

Use a loop or iterate over the lines in the file.使用循环或迭代文件中的行。 Here is how the modified version will look like:修改后的版本如下所示:

import requests
import time

req = requests.session()
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
file_lines = open("codes.txt", "r").readlines()
for line in file_lines:
    param={
        "ID":line
    }

    source = req.post("http://www.example.com/api/", data=param, headers=headers)
    if "valid" in source.text:
        print(source.text)
    else:
        print(source.text)

Since each line is a entry that needs to be checked, you need to repeat the request with different parameter each time.由于每一行都是需要检查的条目,因此您需要每次使用不同的参数重复请求。

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

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