read write in txt in python code example

Example 1: how to write to a text file in python

#the way i learned it
#plus explanations

from sys import * #this is for making it more flexible

#so now we gotta open a file to write in

f = open("haha.txt", "w") # the w means WRITING
#now we gotta write something

f.write(str(argv[1])) # the str means change it into a string of letters
#argv[1] means it's the thing you type after the python run thing
#for example: "python run.py helo"

#now we gotta finish it
f.close()

#if you want to see whats in it...

f = open("haha.txt", "r") #r means READING
print(f.read()) # this prints what you wrote

#example input and output

#            python run.py helo
#   helo

Example 2: Write a Python program to read an entire text file

# Program to read entire 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')