# Program to show various ways to read and write data in a file. # https://www.geeksforgeeks.org/reading-writing-text-files-python/ f = open("myfile.txt", "w") L = ["This is Beijing \n", "This is Paris \n", "This is London \n"] f.write("Hello \n") # \n = new line char f.writelines(L) f.close() print("f.read( ) whole file (text)") print("f.read(n) n chars") print("f.readline() 1 line") print("f.readline(n) min(n chars, 1 line)") print("f.readlines() whole file (list)") print() #---------- f = open("myfile.txt", "r+") print("1.f.read() whole file (text)") print(f.read()) #---------- f.seek(0) print("2.f.read(9) n chars") print(f.read(9)) print() #---------- # seek(n) takes the file handle to the nth byte from the beginning. f.seek(0) print("3.f.readline() 1 line") print(f.readline()) #---------- f.seek(0) print("4.f.readline(9) min(n chars, 1 line)") print(f.readline(9)) #---------- f.seek(0) print("5.f.readlines() whole file (list)") print(f.readlines()) print() f.close()