What is a file?
File is a named location on disk to store related information. It is used to
permanently store data in a non-volatile memory (e.g. hard disk).
Since, random access memory (RAM) is volatile which loses its data when
computer is turned off, we use files for future use of the data.
File handling is an integral part of programming. File handling in Python is
simplified with built-in methods, which include creating, opening, and closing files.
While files are open, Python additionally allows performing various file operations,
such as reading, writing, and appending information.
Types Of File in Python
There are two types of files in Python and each of them are explained below in detail
with examples for your easy understanding.
They are:
Binary file
Text file
Binary files in Python
Most of the files that we see in our computer system are called binary files.
Example:
1. Document files: .pdf, .doc, .xls etc.
2. Image files: .png, .jpg, .gif, .bmp etc.
3. Video files: .mp4, .3gp, .mkv, .avi etc.
4. Audio files: .mp3, .wav, .mka, .aac etc.
5. Database files: .mdb, .accde, .frm, .sqlite etc.
6. Archive files: .zip, .rar, .iso, .7z etc.
7. Executable files: .exe, .dll, .class etc.
Text files in Python
Text files don’t have any specific encoding and it can be opened in normal text editor
itself.
Example:
Web standards: html, XML, CSS, JSON etc.
Source code: c, app, js, py, java etc.
Documents: txt, tex, RTF etc.
Tabular data: csv, tsv etc.
Configuration: ini, cfg, reg etc.
Hence, in Python, a file operation takes place in the following order.
1. Open a file
2. Read or write (perform operation)
3. Close the file
How to open a file?
Python has a built-in function open() to open a file. This function returns a
file object
The open() Python method is the primary file handling function.
The basic syntax is:
file_object = open('file_name', 'mode')
The open() function takes two elementary parameters for file handling:
1. The file_name includes the file extension and assumes the file is in the
current working directory. If the file location is elsewhere, provide the
absolute or relative path.
2. The mode is an optional parameter that defines the file opening method.
The table below outlines the different possible options:
Modes Description
r Opens a file for reading only.
rb Opens a file for reading only in binary format.
r+ Opens a file for both reading and writing.
rb+ Opens a file for both reading and writing in binary format.
w Opens a file for writing only.
wb Opens a file for writing only in binary format.
w+ Opens a file for both writing and reading.
wb+ Opens a file for both writing and reading in binary format.
a Opens a file for appending.
ab Opens a file for appending in binary format.
a+ Opens a file for both appending and reading.
ab+ Opens a file for both appending and reading in binary format.
Modes Description
r Opens a file for reading only.
rb Opens a file for reading only in binary format.
r+ Opens a file for both reading and writing.
rb+ Opens a file for both reading and writing in binary format.
w Opens a file for writing only.
wb Opens a file for writing only in binary format.
w+ Opens a file for both writing and reading.
wb+ Opens a file for both writing and reading in binary format.
a Opens a file for appending.
ab Opens a file for appending in binary format.
a+ Opens a file for both appending and reading.
ab+ Opens a file for both appending and reading in binary format.
Take a look at this program and analyse how the reading mode works:
Example
f = open("[Link]",
"r") print([Link]())
Output:
Hello World
Hello Python
Good Morning
The close() method
Once all the operations are done on the file, we must close it through our
Python script using the close() method. Any unwritten information gets
destroyed once the close() method is called on a file object.
We can perform any operation on the file externally using the file system
which is the currently opened in Python; hence it is good practice to close
the file once all the operations are done.
The syntax to use the close() method is given below.
Syntax
[Link]()
# opens the file [Link] in read mode
fileptr = open("[Link]","r")
if fileptr:
print("file is opened successfully")
#closes the opened file
[Link]()
The with statement
The with statement was introduced in python 2.5. The with statement is
useful in the case of manipulating the files. It is used in the scenario where a
pair of statements is to be executed with a block of code in between.
The syntax to open a file using with the statement is given below.
with open(<file name>, <access mode>) as <file-pointer>:
#statement suite
The advantage of using with statement is that it provides the guarantee to
close the file regardless of how the nested block exits.
It is always suggestible to use the with statement in the case of files
because, if the break, return, or exception occurs in the nested block of code
then it automatically closes the file, we don't need to write
the close() function. It doesn't let the file to corrupt.
Consider the following example.
Example
with open("[Link]",'r') as f:
content = [Link]();
print(content)
Python Read From File
In order to read a file in python, we must open the file in read mode.
There are three ways in which we can read the files in python.
read([n])
readline([n])
readlines()
Read Only Parts of the File
By default the read() method returns the whole text, but you can also
specify how many characters you want to return:
Return the 5 first characters of the file:
f = open("[Link]", "r")
print([Link](5))
Read Lines
Using this function we can read the content of the file on a line by line basis. You can
return one line by using the readline() method:
Read one line of the file:
f = open("[Link]", "r")
print([Link]())
By looping through the lines of the file, you can read the whole
file, line by line:
f = open("[Link]", "r")
for x in f:
print(x)
Here we are reading all the lines present inside the text file
including the newline characters.
f = open("[Link]", "r")
print([Link]())
Perform Write operation
The write() file method
Python provides a write() method to write a string or bytes sequence to a file. This
function returns a number that is the size of data stored in a single Write call.
The write() method write() method takes a string as an argument and writes
it to the text file.
It returns the number of characters being written on single execution of the
write() method.
Also, we need to add a newline character (\n) at the end of every sentence to
mark the end of line.
To write some text to a file, we need to open the file using the open
method with one of the following access modes.
w: It will overwrite the file if any file exists. The file pointer is at the
beginning of the file.
a: It will append the existing file. The file pointer is at the end of the
file. It creates a new file if no file exists.
We have two methods for writing data into a file as shown below.
write(string)
writelines(list)
write(string)
Example :
# Python code to create a file
file = open('[Link]','w')
[Link]("This is the write command")
[Link]("It allows us to write in a particular file")
[Link]()
writelines() method
The writelines() method This method is used to write multiple strings to a file. We
need to pass an iterable object like lists, tuple, etc. containing strings to the
writelines() method.
fruits = [“Apple\n”, “Orange\n”, “Grapes\n”, “Watermelon”]
my_file = open(“[Link]”, “w”)
my_file.writelines(fruits)
Python Append to File
To append data into a file we must open the file in ‘a+’ mode so that we will have
access to both the append as well as write modes.
Ex1 :
my_file = open(“[Link]”, “a+”)
my_file.write (“Strawberry”)
Ex2:
fruits = [“\nBanana”, “\nAvocado”, “\nFigs”, “\nMango”]
my_file = open(“[Link]”, “a+”)
my_file.writelines(fruits)
Python OS module
Renaming the file
The Python os module enables interaction with the operating system. The os
module provides the functions that are involved in file processing operations
like renaming, deleting, etc. It provides us the rename() method to rename
the specified file to a new name. The syntax to use the rename() method is
given below.
Syntax:
rename(current-name, new-name)
The first argument is the current file name and the second argument is the
modified name. We can change the file name bypassing these two
arguments.
Example 1:
import os
#rename [Link] to [Link]
[Link]("[Link]","[Link]")
Removing the file
The os module provides the remove() method which is used to remove the
specified file. The syntax to use the remove() method is given below.
remove(file-name)
Example 1
import os;
#deleting the file named [Link]
[Link]("[Link]")