python how to read text file code example

Example 1: get text from txt file python

with open ("data.txt", "r") as myfile:
    data = myfile.read().splitlines()

Example 2: open text file in python

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

Example 3: open file python

with open('filename', 'a') as f: # able to append data to file
	f.write(var1) # Were var1 is some variable you have set previously
	f.write('data') 
	f.close() # You can add this but it is not mandatory 

with open('filename', 'r') as f: # able to read data from file ( also is the default mode when opening a file in python)

with open('filename', 'x') as f: # Creates new file, if it already exists it will cause it to fail

with open('filename', 't') as f: # opens the file in text mode (also is defualt)

with open('filename', 'b') as f: # Use if your file will contain binary data
  
with open('filename', 'w') as f: # Open file with ability to write, will also create the file if it does not exist (if it exists will cause it to fail)
  
with open('filename', '+') as f: # Opens file with reading and writing

# You can combine these as you like with the + for reading and writing

Example 4: 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 5: how to open a text file in python

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

Example 6: reading text file in python

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