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# Program to write multiple lines to text file using writelines() function
2with open("python.txt", "w") as file:
3 content = ["Hello\n", "Welcome to Python Tutorial\n", "Cheers \n" ]
4 file.writelines(content)
5 file.close()
6
7# Program to read the entire file (absolute path) using read() function
8with open("C:/Projects/Tryouts/python.txt", "r") as file:
9 content = file.read()
10 print(content)
11 file.close()