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("hello.txt", "w") as f:
2 f.write("Hello World")
3#using With Statement files opened will be closed automatically
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 to text file using write() function
2with open("python.txt", "w") as file:
3 content = "Hello, Welcome to Python Tutorial !! \n"
4 file.write(content)
5 file.close()
6
7
8# Program to read the entire file (absolute path) using read() function
9with open("C:/Projects/Tryouts/python.txt", "r") as file:
10 content = file.read()
11 print(content)
12 file.close()