1

I am attempting to take the printed output of my code and have it appended onto a file in python. Here is the below example of the code test.py:

import http.client

conn = http.client.HTTPSConnection("xxxxxxxxxxxx")

headers = {
    'Content-Type': "xxxxxxxx",
    'Accept': "xxxxxxxxxx",
    'Authorization': "xxxxxxxxxxxx"
    }

conn.request("GET", "xxxxxxxxxxxx", headers=headers)

res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))

This prints out a huge amount of text onto my console.

My goal is to take that output and send it over to an arbitrary file. An example I can think of that I've done on my terminal is python3 test.py >> file.txt and this shows me the output into that text file.

However, is there a way to run something similar to test.py >> file.txt but within the python code?

2

2 Answers 2

1

You could open the file in "a" (i.e., append) mode and then write to it:

with open("file.txt", "a") as f:
   f.write(data.decode("utf-8"))
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the included module for writing to a file.

with open("test.txt", "w") as f:
    f.write(decoded)

This will take the decoded text and put it into a file named test.txt.

import http.client

conn = http.client.HTTPSConnection("xxxxxxxxxxxx")

headers = {
    'Content-Type': "xxxxxxxx",
    'Accept': "xxxxxxxxxx",
    'Authorization': "xxxxxxxxxxxx"
}

conn.request("GET", "xxxxxxxxxxxx", headers=headers)

res = conn.getresponse()
data = res.read()

decoded = data.decode("utf-8")
print(decoded)

with open("test.txt", "w") as f:
    f.write(decoded)

1 Comment

this was what I was looking for. I was unable to visualize it correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.