I've looked over SO and I have not been able to find the answer that I am looking for.
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?
CodePudding user response:
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"))
CodePudding user response:
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)