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# Reference https://docs.python.org/3/library/functions.html#open
2
3# Method 1
4file = open("welcome.txt", "r") # mode can be r(read) w(write) and others
5data = file.read()
6file.close()
7
8# Method 2 - automatic close
9with open("welcome.txt") as infile:
10 data = file.read()
11
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