1r for reading
2r+ opens for reading and writing (cannot truncate a file)
3w for writing
4w+ for writing and reading (can truncate a file)
5rb for reading a binary file. The file pointer is placed at the beginning of the file.
6rb+ reading or writing a binary file
7wb+ writing a binary file
8a+ opens for appending
9ab+ Opens a file for both appending and reading in binary. The file pointer is at the end of the file if the file exists. The file opens in the append mode.
10x open for exclusive creation, failing if the file already exists (Python 3)
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()
1with open("test.txt",'w',encoding = 'utf-8') as f:
2 f.write("my first file\n")
3 f.write("This file\n\n")
4 f.write("contains three lines\n")
1# using 'with' block
2
3with open("xyz.txt", "w") as file: # xyz.txt is filename, w means write format
4 file.write("xyz") # write text xyz in the file
5
6# maunal opening and closing
7
8f= open("xyz.txt", "w")
9f.write("hello")
10f.close()
11
12# Hope you had a nice little IO lesson
1f = open("demofile3.txt", "w")
2f.write("Woops! I have deleted the content!")
3f.close()
4
5#open and read the file after the appending:
6f = open("demofile3.txt", "r")
7print(f.read())