1import sys
2
3# only this print call will write in the file
4print("Hello Python!", file=open('output.txt','a'))
5
6# not this one (std output)
7print("Not written")
8
9# any further print will be done in the file
10sys.stdout = open('output.txt','wt')
11print("Hello Python!")
1#first arg is the name of the file
2#second arg notes that the file is open to write to it
3outputFile = open("fileName", "w")
4#next line writes to the file
5outputFile.write(str)
6#remember to close opened files
7outputFile.close()
1>>> with open('workfile') as f:
2... read_data = f.read()
3
4>>> # We can check that the file has been automatically closed.
5>>> f.closed
6True
7