TransWikia.com

How to add n after every line in a txt file python

Stack Overflow Asked by Zeko on December 18, 2021

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.

1234
12345
12346

And after that i send a request to verify if the id is valid or not.

So when im checking and adding multiple ids in that txt file it becomes 1 id 123412345123456

How i can add a n to every line and make a request for every id.

One Answer

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.

Answered by Raz Crimson on December 18, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP