read write in txt in python code example
Example 1: how to write to a text file in python
from sys import *
f = open("haha.txt", "w")
f.write(str(argv[1]))
f.close()
f = open("haha.txt", "r")
print(f.read())
Example 2: 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')