Python - Python Advanced - File Handling Tutorial
File handling allows users to handle files i.e. to read and write files, along with many other file handling options, to operate on files.
Opening a file is the first step to performing any action on the file.
Data read from the file is always a string format.
Opening files in python
Python has a built-in open()
function to open a file. The open()
function takes two parameters; filename and mode.
Syntax-
file = open(‘filename.extension’, ‘mode’)
There are different methods (modes) for opening a text file(default):
-
read mode - 'r' - Default value.
-
write mode -'w'.
-
append mode - 'a'
-
create mode - 'x' - Creates the specified file, returns an error if the file exists
-
read and write mode - 'r+'
-
write and read mode - 'w+'
-
append and read mode - 'a+'
There are different methods (modes) for opening a binary file:
-
read mode - 'rb'
-
write mode -'wb'
-
append mode - 'ab'
-
read and write mode - 'r+b'
-
write and read mode - 'w+b'
-
append and read mode - 'a+b'
There are different methods for a file object
-
read - reading the content of the file
-
write - write the content to the file
-
tell - tell the cursor location
-
seek - moves the cursor to the specific location
Example-
fresherbell.txt
Welcome to freshebell.com
Python Support file handling and allows user to handle file.
Default mode used in file handling is read mode
Read Mode-
-
It is the default mode.
-
If the file exists then it will then It open a file for reading and places the cursor at the begining of the file
-
It will throw an error if the file does not exist.
-
Only reading is allowed, and writing to a file is not allowed.
Example-
# a file named "fresherbell", will be opened with the reading mode.
file = open('fresherbell.txt', 'r')
# This will print every line one by one in the file
for each in file:
print (each)
Output-
Welcome to freshebell.com
Python Support file handling and allows user to handle file.
Default mode used in file handling is read mode
Reading file in python
Using read() and read(size)
-
read() - reads the whole content of the file and returns a string object
-
read(size) - reads the specified no of characters from the current position and returns the string
Using the read(size) method we can read files. If the size is mentioned, then It will read the data depending on the size character by character. Otherwise, it will read the whole file.
Example-
file = open("fresherbell.txt",'r')
print(file.tell())
# read the first 7 character
print(file.read(7))
print(file.tell())
Output-
0
Welcome
7
Again running the file.read() method will read the next character.
Similarly tell() return the current position.
# read the next 14 character
print(file.read(14))
print(file.tell())
Output-
to freshebell
21
To come back to 0 or any position, we can use seek() function
Example-
file.seek(0)
print(file.tell())
print(file.read(7))
Output-
0
Welcome
If size is not mentioned, it will read whole data
Example-
file = open("fresherbell.txt",'r')
# read the whole data
file.read()
Output-
'Welcome to freshebell.com\nPython Support file handling and
allows user to handle file.\nDefault mode used in file handling
is read mode\nclose() is used to save and exit the file'
Using readline() & readlines()
-
readline() - reads the current line from the current position of the cursor and returns a string object
-
readlines() - reads the whole content of the file and returns a list of strings where every element is a string and represents a line
Example-
file = open("fresherbell.txt",'r')
# return current position i.e 0
print(file.tell())
# return line from the current position, will also return \n
print(file.readline())
# moving cursor to 10th position
file.seek(10)
# reading line from 10th position, will also return \n
print(file.readline())
# cursor will moved to the last position of current line
print(file.tell())
#return whole content in the form of list in the form of string from current cursor position
print(file.readlines())
Output-
0
Welcome to freshebell.com
freshebell.com
26
['Python Support file handling and allows user to handle file.\n', 'Default mode used in file handling is read mode']
Write Mode-
-
If a file exists then it opens a file for writing and deleted the content of file.
-
It will create the file if it does not exist.
-
Only writing is allowed, and reading a file is not allowed.
-
After writing,closing of the file is required to save and exit
Example-
# a file named "fresherbell", will be opened with the write mode.
file = open('fresherbell.txt', 'w')
Writing to a file
Example-
# finding the current cursor position
print(file.tell())
# writing to a file
file.write('Freshebell')
# finding the updated cursor position
print(file.tell())
# closing the file to save and exit
file.close()
Output-
0
10
fresherbell.txt
Freshebell
Reading is not allowed in file opened by write mode-
Example-
file = open('fresherbell.txt', 'w')
file.write('Freshebell')
file.read()
Output-
---------------------------------------------------------------------------
UnsupportedOperation Traceback (most recent call last)
Input In [37], in <cell line: 3>()
1 file = open('fresherbell.txt', 'w')
2 file.write('Freshebell')
----> 3 file.read()
UnsupportedOperation: not readable
Append Mode-
-
If a file exists it will open a file for appending in write mode and places the cursor at the end of the file, creating the file if it does not exist.
-
Only writing is allowed, and reading a file is not allowed.
-
Append will always write the content at the end of the file so seek() will not work here
Example
# a file named "fresherbell", will be opened with the append mode.
file = open('fresherbell.txt', 'a')
fresherbell.txt
Fresherbell
Appending to a file
file = open('fresherbell.txt' , 'a')
print(file.tell())
file.write(' hello world')
print(file.tell())
file.close()
Output-
10
22
After appending fresherbell.txt
Freshebell hello world
Write and read mode - 'w+'
-
If the file exists then it will open the file in write mode and deletes the content of the file
-
if the file does not exist then it will create a file with the given name and extension
-
You are allowed to write into the file and also allowed to read from the file
Example-
# a file named "fresherbell", will be opened with the write and read mode.
file = open('fresherbell.txt' , 'w+')
print(file.tell())
file.write('Python file handling')
print(file.tell())
file.seek(0)
print(file.tell())
print(file.read())
f.close()
Output-
0
20
0
Python file handling
In the above program if read() is perform before write(). Then it will show an empty file. Because in w+ mode it will delete the content of the file first and then perform a write operation.
Example-
file = open('fresherbell.txt' , 'w+')
print(file.tell())
print(file.read())
file.write('Python file handling')
print(file.tell())
f.close()
Output-
0
20
Read and write - 'r+'
-
If the file exists then it will open the file in reading mode and places the cursor at the beginning of the file
-
if the file does not exist then it will give FileNotFoundError
-
You are allowed to write into the file and also allowed to read from the file
Example-
file = open('fresherbell.txt' , 'r+')
print(file.tell())
print(file.read())
print(file.tell())
file.write('Using r+ - read and write')
print(file.tell())
f.close()
Output-
0
Python file handling
20
45
Append and read mode - 'a+'
-
If the file exists then it will open the file in append mode and places the cursor at the end of the file
-
if the file does not exist then it will create a file with the given name and extension
-
You are allowed to write into the file and also allowed to read from the file
-
the append will always write the content at the end of the file so seek() will not work here.
freshebell.txt
Hello Python
Example-
file = open('fresherbell.txt','a+')
# cursor is at last position,so it will return last position index
print(file.tell())
# moving cursor to 5th position
file.seek(5)
# Even the cursor is at 5th position,but append will only happen at last position
file.write('hello')
# It will return empty string because now the cursor again moved to last position
print(file.read())
# moving cursor to 0th position
file.seek(0)
# It will return full string because now the cursor is at 0th postion
print(file.read())
# It will return last position,because cursor again moved to last due to read()
print(file.tell())
# save and exit the file
file.close()
Output-
12
Hello Pythonhello
17
Using with statement
Let's assume the fresherbell.txt file is empty. then using with the statement, will try to perform a write operation on it using writelines()-
Using with statement with writelines(). we no need to call file.close(). It will automatically close it.
Example-
with open('fresherbell.txt','w') as file:
file.writelines(['100\n' , '200\n' , '300\n'])
Output in fresherbell.txt file-
100
200
300