1#there are many modes you can open files in. r means read.
2file = open('C:\Users\yourname\files\file.txt','r')
3text = file.read()
4
5#you can write a string to it, too!
6file = open('C:\Users\yourname\files\file.txt','w')
7file.write('This is a typical string')
8
9#don't forget to close it afterwards!
10file.close()
1with open("output.txt", "a") as f:
2 print("Hello StackOverflow!", file=f)
3 print("I have a question.", file=f)
4
1import sys
2
3print('This message will be displayed on the screen.')
4
5original_stdout = sys.stdout # Save a reference to the original standard output
6
7with open('filename.txt', 'w') as f:
8 sys.stdout = f # Change the standard output to the file we created.
9 print('This message will be written to a file.')
10 sys.stdout = original_stdout # Reset the standard output to its original value