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.
Syntax of File Opening
1 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# 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() |