how to use text files in python code example

Example 1: open text file in python

f=open("Diabetes.txt",'r')
f.read()

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')

Example 3: python output to text file

$ python my_program.py > output.txt

Example 4: reading text file in python

>>> year = 2016
>>> event = 'Referendum'
>>> f'Results of the {year} {event}'
'Results of the 2016 Referendum'