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?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
hachemon
  • 158
  • 8
  • Does this answer your question? [How to redirect 'print' output to a file?](https://stackoverflow.com/questions/7152762/how-to-redirect-print-output-to-a-file) – luk2302 Dec 30 '22 at 18:43
  • Does this answer your question? [How to output to the console and file?](https://stackoverflow.com/questions/11325019/how-to-output-to-the-console-and-file) – evces Dec 30 '22 at 18:43

2 Answers2

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"))
Mureinik
  • 297,002
  • 52
  • 306
  • 350
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)
MrDiamond
  • 958
  • 3
  • 17