In this Article we going to learn following topics :
- Read data from a file.
- Write data to a file .
- Append Data to a file.
- Delete a file.
We're going to cover each of the above point with meaningful examples.
In python open() function is used to perform various operations on files, operation such as
(read,write,append,delete).
open()
Syntax :- open(filename, mode)
The open() function takes two argument filename and mode, and return a TextIOWrapper class object.
There are four different modes available :-
r mode is the default when no mode passed, used to read file, it throws FileNotFoundError if the file passed in first argument does not exist.
w mode is write data into a file, if data exist in the file it removes that data then, start writing the data into the file , if the filename passed does not exist,it creates a new file.
a mode write data to existing file, creates a file if it does not exist.
delete file with specified filename using os module ,if the file does not exist it throws FileExistsError error.
Other then that , you are specify the mode in which file will we handled.
- t in Text mode.
b in Binary mode.
For Example :-
file1 = open("file.txt",'wb') # means write in binary mode
file2 = open("file.txt",'wt') # means write in text mode
Default mode is Text mode
After doing all the operation on file use can call file.close() method to close a file.
Throughout the examples we're going to us the below file
- filename :- students.txt
Name : Ram Kumar
Age : 13
City : Ajmir
Name : Alice Pen
Age : 12
City : Boston
Name : Marcus Lee
Age : 15
City : Tokyo
Read data from file
file = open("students.txt",'r')
for line in file:
print(line,end="")
file.close()
Output :-
Name : Ram Kumar
Age : 13
City : Ajmir
Name : Alice Pen
Age : 12
City : Boston
Name : Marcus Lee
Age : 15
City : Tokyo
In the above code , used for to the read one line at a time and print it, we're added end="" in print statement because , in file , a line ends with \n implicitly.
Write data to file
file = open("students_2.txt",'w')
student_info = {
"Name" : "Mike Javen",
'Age' : 15,
'City' : 'Minisoda'
}
for field,data in student_info.items():
file.write(f"{field} : {data} \n")
file.close()
students_2.txt file content :-
Name : Mike Javen
Age : 15
City : Minisoda
Here, we have used write() function , new file students_2.txt gets created, because it does not exist in the first place ,and we have added a student info to that file, we not added this student data to students.txt file because in w mode the data in the file first gets deleted and then writing starts.
Append data to file
file = open("students.txt",'a')
students_info = [ {
"Name" : "John Lenon",
'Age' : 14,
'City' : 'Navi Mumbai'
},
{
"Name" : "Sam Dune",
'Age' : 11,
'City' : 'Boston'
}
]
for student_info in students_info:
file.write("\n")
for field,data in student_info.items():
file.write(f"{field} : {data} \n")
file.close()
Students.txt file.content :-
Name : Ram Kumar
Age : 13
City : Ajmir
Name : Alice Pen
Age : 12
City : Boston
Name : Marcus Lee
Age : 15
City : Tokyo
Name : John Lenon
Age : 14
City : Navi Mumbai
Name : Sam Dune
Age : 11
City : Boston
In the above code we added 2 new students details in students.txt file using 'a' append mode,
Delete a file
import os
filename = 'students_2.txt'
os.remove(filename)
print(f"successfully deleted file {filename}")
Output :-
successfully deleted file students_2.txt
The above example is fairly simple one in which we import python os module to delete the file in the current directory i.e., students_2.txt if the file does not exist in the diretory it throws error FileNotFoundError error.
With this we have seen all 4 opearation on a file, I'd like to mention another way in which we can perform same opeartions we talked about, where we does not have to explicitly close() the file working with the file.
Alternative way
with open("students.txt",'r') as file:
for line in file:
print(line, end="")
Output :-
Name : Ram Kumar
Age : 13
City : Ajmir
Name : Alice Pen
Age : 12
City : Boston
Name : Marcus Lee
Age : 15
City : Tokyo
Name : John Lenon
Age : 14
City : Navi Mumbai
Name : Sam Dune
Age : 11
City : Boston
Here, we have used with keyword and as alias as soon as the with block ends, the file gets closed implicitly, we can use the same syntax with other modes
Writing file in Binary Mode
file = open("new_students.txt",'wb')
students_info = b'''
"Name" : "Sam Dune",
'Age' : 11,
'City' : 'Boston'
}
'''
file.write(students_info)
file.close()
Output :-
"Name" : "Sam Dune",
'Age' : 11,
'City' : 'Boston'
Here we have write bytes to a files
Before Finishing this Article I'd like to cover some useful examples of file processing.
Example :-
- Reading the entire file content and storing it list for further processing
# file content :-
#my name is john levi and i
#live in boston and study in
#xyz univeristy doing majors
#in computer science.
person_info = [line for line in open('info.txt')]
for line in person_info:
print(line,end="")
Output :-
my name is john levi and i
live in boston and study in
xyz univeristy doing majors
in computer science.
Here we fetched the content of entire file using list compreshension in just single line remember this file could be of 1000 of line for some operation we have to read file again and again, in this way we can just used the file content stored in the list.
Example :-
Reading the file content and storing it content in some collection like dictionaries datatype
# File Content :-
# Ram Kumar , 12 , Indore
# Shayam Kumar, 13 , Mumbai
# Ajay Kumar, 11 , Delhi
# Harris javen, 15 , New Jersey
students_info = []
for line in open("info.txt"):
name, age, city = line.split(',')
student = {
"Name" : name.strip(),
"Age" : age.strip(),
"City" : city.strip()
}
students_info.append(student)
print("Content tetched from file and stored in dictionary\n")
for student in students_info:
print(student)
Output :-
Content tetched from file and stored in dictionary
{'Name': 'Ram Kumar', 'Age': '12', 'City': 'Indore'}
{'Name': 'Shayam Kumar', 'Age': '13', 'City': 'Mumbai'}
{'Name': 'Ajay Kumar', 'Age': '11', 'City': 'Delhi'}
{'Name': 'Harris javen', 'Age': '15', 'City': 'New Jersey'}
with this example we have come to an end hope you all have understood the topics covered in this article.
:-)
Top comments (0)