1file = open("text.txt", "w")
2file.write("Your text goes here")
3file.close()
4'r' open for reading (default)
5'w' open for writing, truncating the file first
6'x' open for exclusive creation, failing if the file already exists
7'a' open for writing, appending to the end of the file if it exists
1file = open(“testfile.txt”,”w”)
2
3file.write(“Hello World”)
4file.write(“This is our new text file”)
5file.write(“and this is another line.”)
6file.write(“Why? Because we can.”)
7
8file.close()
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!")
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
11
1with open("file.txt", "w") as file:
2 for line in ["hello", "world"]:
3 file.write(line)