0

I was creating a loop to send HTTP requests taking data from a txt file but in the variable I get a line break that I don't know how to remove:

import requests

file = open("uuids.txt", "r")

for uuid in file:
    url = 'http://ip:port/api/assets/changeAssetTemplates/{}'.format(uuid)
    headers = {
        ...
    }
    print(url)
    response = requests.request("GET", url, headers=headers)
    print(response.text)

The first print paints this:

http://ip:port/api/assets/changeAssetTemplates/f4c71dd5-13af-428a-a3a5-4cbaf10d9bd3

A good URL. But the second print paints the error from the request:

{"timestamp":1563971402621,"status":404,"error":"Not Found","message":"No message available","path":"/api/assets/changeAssetTemplates/f4c71dd5-13af-428a-a3a5-4cbaf10d9bd3%0A"}

Where we can see that the data you get from the uuid variable is making a line break (%0A) and I would like to know how to avoid this problem.

By the way, an example of uuids.txt:

f4c71dd5-13af-428a-a3a5-4cbaf10d9bd3
1a71d6dc-a9b3-43fa-b675-747af9d7c202
2465ea64-3334-44b1-8f23-16e4df3aeea1
2fb98bba-d03d-495a-b5a2-9656bf623854
7a2aca40-dc5c-4aec-b700-7d0a91d39dd8
983ce44b-ab24-49bb-b128-8a30712dc2ca
2487e2ed-bff5-4195-ab5e-875210e634b0
965c62da-7c7a-4bf3-a0b8-de60d9b392dd
8b9bcf8c-0163-48cc-8603-3447ab7f29f6
0a7a5db9-67be-4a2a-af58-0189565caa2d
Kevimuxx69
  • 109
  • 1
  • 7

2 Answers2

1

Just remove line breaks from uuid like this :

for uuid in file:
    url = 'http://ip:port/api/assets/changeAssetTemplates/{}'.format(uuid.replace('\n',''))
    headers = {
        ...
    }
    print(url)
    response = requests.request("GET", url, headers=headers)
    print(response.text)

Carefull if you're on windows, line breaks might be '\r\n' instead of '\n';

Clem G.
  • 396
  • 3
  • 8
  • 1
    `uuid = uuid.strip()` is the Pythonesque way to remove all trailing and leading whitespace, and it takes care of `\r\n` too. – AKX Jul 24 '19 at 12:49
0

You can simply remove least char in uuid:

url = 'http://ip:port/api/assets/changeAssetTemplates/{}'.format(uuid[:-1])

Another solution:

url = 'http://ip:port/api/assets/changeAssetTemplates/{}'.format(uuid.rstrip("\n"))

PS: Python documentation of readline method https://docs.python.org/3.3/tutorial/inputoutput.html:

f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n', a string containing only a single newline.

domino_pl
  • 163
  • 1
  • 1
  • 7