Python 3 File Handling Script to Open,Read and Write Files From Local Directory Tutorial | Different Modes of File Access Modes in Python

Python 3 File Handling Script to Open,Read and Write Files From Local Directory Tutorial | Different Modes of File Access Modes in Python

 

Welcome folks today in this tutorial we will be open,read and write files using python 3. In this tutorial we will be seeing different modes of file opening.

 

The various modes of file opening in python are:

 

Read Only (‘r’):  In this mode we will be granting access to only read the files to the user.

 

Read and Write (‘r+’): In this mode we will be granting access to only read and write the files to the user

 

Write Only (‘w’) :  In this mode we only grant write access to the user to write the files.

 

Write and Read (‘w+’): In this mode we grant access to write and read the files.

 

Append Only (‘a’):  In this mode we grant access for writing to an existing file and cursor is positioned at end of file. It will append to the existing content.

 

Append and Read (‘a+’): In this mode we will be granting access for appending and reading the files.

READ  Python 3 Tkinter Tic Tac Toe Multiplayer Game Script Using Numpy Library GUI Desktop App Full Project For Beginners

 

 

 

Syntax of File Opening

 

 

File_object = open(r"File_Name", "Access_Mode")

 

 

 

Here we are using the open method of python to interact with files inside local directory in python. The first argument is the filename and secondly is the access mode.

 

 

 

Example to read file

 

 

# Python program to demonstrate 
# opening a file 


# Open function to open the file "myfile.txt" 
# (same directory) in read mode and store 
# it's reference in the variable file1 

file1 = open("myfile.txt") 

# Reading from file 
print(file1.read()) 

file1.close()

 

 

 

Appending or Writing to Existing File

 

 

# Python program to demonstrate 
# opening a file 


# Open function to open the file "myfile.txt" 
# (same directory) in append mode and store 
# it's reference in the variable file1 
file1 = open("myfile.txt", "a") 

# Writing to file 
file1.write("\nWriting to file :)") 

# Closing file 
file1.close()

 

 

Leave a Reply