read write text file python code example
Example 1: python writing to text file
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
f = open("demofile2.txt", "r")
print(f.read())
Example 2: python write to file
file = open(“testfile.txt”,”w”)
file.write(“Hello World”)
file.write(“This is our new text file”)
file.write(“and this is another line.”)
file.write(“Why? Because we can.”)
file.close()
Example 3: python open and read file with
with open('pagehead.section.htm','r') as f:
output = f.read()
Example 4: Write a Python program to read an entire text file
import os
PATH = "H:\\py_learning\\interviewsprep"
os.chdir(PATH)
def file_read(fname,mode='r+'):
try:
with open(fname) as txt:
print(txt.read())
print('>>>>>>>>>>>>>>>')
except FileNotFoundError:
print("check file existance in current working directory i.e : ",os.getcwd())
print('provide file existance path to PATH variable')
finally:
pass
file_read('file1.txt')