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("file.txt", "w") as file:
2 for line in ["hello", "world"]:
3 file.write(line)
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
1# Basic syntax:
2file_object = open("filename", "mode")
3file_object.write("Data to be written")
4file_object.close()
5
6# Example usage:
7file_object = open("/path/to/my_filename.txt", "w") # w = write, r = read
8file_object.write("Line of text to write")
9file_object.close()
1with open("testfile.txt", "w") as f:
2 # "w" - write into file
3 # "r" - read into file
4 # "+" - read and write into file
5 f.write("Hello World")