hachemon
hachemon

Reputation: 158

How do I append an output text onto a file in python

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?

Upvotes: 1

Views: 89

Answers (2)

MrDiamond
MrDiamond

Reputation: 1072

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)

Upvotes: 1

Mureinik
Mureinik

Reputation: 310983

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"))

Upvotes: 1

Related Questions