What is File Handling in Python?
File handling is an important part of programming. There are built-in methods in Python that make it easier to create, open, and close files.
Once files are open, you can do different things with them, like read, write, and add information.
As with other Python concepts, the implementation of the file-handling concept is straightforward and concise.
In contrast, the implementation of this concept in other languages is either complex or lengthy.
File Handling Functions in Python
Python’s most important functions for working with files are open(), close(), read(), write() and append().
1. open() Function
The open() function in Python takes two arguments: the file name and the access mode.
This function returns a file object, which can be used to carry out various operations such as reading and writing.
Syntax:
file object = open(<file-name>, <access-mode>, <buffering>)
Here are the access modes that can be used with the open() function:
- r: The open() function’s default mode is to start reading from the beginning of the file.
This also opens the file in read-only mode.
- rb: Opens the file as a binary file that can only be read and starts reading from the beginning.
Even though binary format can be used for different things, it is most often used to store images, videos, etc.
- r+: Opens a file so that you can read and write to it. The file pointer is moved to the beginning of the file.
- w: The file pointer is put at the beginning of the file, and any other file with the same name will be erased. It will create a new file if there isn’t already one with the same name. This also opens the file in write-only mode.
- wb: Opens a write-only file in binary mode.
- w+: Opens a file for writing and reading.
- wb+: Opens a file for writing and reading in binary mode.
- a: Opens a file so that new information can be appended to it. The pointer is put at the file’s end. If there isn’t already a file with the same name, a new one is made.
- ab: Opens a file for appending in binary mode.
- a+: Opens a file for both appending and reading.
- ab+: Opens a file for both appending and reading in binary mode.
Example:
sample1 = open("MyFile.txt") # open file in current directory
sample1 = open("C:/MyFile.txt") # specifying full path
This will open a text file called “MyFile” in read-only mode. The “read” mode is the default mode for the open function.
sample1 = open("MyFile.txt") # equivalent to 'r' or 'rt'
sample1 = open("MyFile.txt",'w') # write in text mode
sample1 = open("img.png",'r+b') # read and write in binary mode
The character ‘a’ doesn’t represent the number 97 in other languages, only when using ASCII encoding.
Moreover, the default encoding is platform-dependent. In Windows, it’s cp1252, but in Linux, it’s utf-8. So, we can’t rely on the default encoding either, or our code will act differently on different platforms.
Because of this, it is very important to specify the encoding type when working with files in text mode.
2. close() Function
Once everything has been done with the file, we must close it with the close() method in our Python script.
When the close() method is called on a file object, any information that hasn’t been written yet is lost.
It’s best to close a file once you’re done with all the operations. You can do this externally using the file system that’s currently open in Python.
Syntax:
fileobject.close()
Example:
sample1 = open ("MyFile.txt", "r")
print(sample1.read())
sample1.close()
After closing the file, we can no longer perform any operations on it. Make sure to close the file correctly to avoid any errors while trying to perform actions on it.
To solve this kind of problem, we should do the following.
try:
sample1 = open("MyFile.txt")
# perform file operations
finally:
sample1 .close()
3. Writing the file
To write text to a file, we need to open the file with the open method and one of the following access modes.
w: This access mode will overwrite the file if any file exists. The file pointer is at the file’s beginning.
a: This will append the existing file and it will create a new file if no file exists. The file pointer is at the end of the file.
Example 1:
# open MyFile.txt so that you can write to it. Make a new file if there isn't already one.
sample1 = open("MyFile.txt", "w")
# overwriting the content to the file
sample1.write('''''Welcome to ITSourceCode Tutorial.
Where we will learn Python the easiest way possible.''')
# closing the opened the file
sample1.close()
Output:
MyFile.txt
Welcome to ITSourceCode Tutorial.
Where we will learn Python the easiest way possible.
Snapshot of the MyFile.txt:
We have opened a new file in write mode. The file didn’t exist previously, but we have created it and written content to it using the write() function.
Example 2:
# open MyFile.txt in append mode.
sample1 = open("MyFile.txt", "a")
# appending the content to the file
sample1.write(" Python is very easy to learn language and Python is Fun!")
# closing the opened the file
sample1.close()
Output:
Welcome to ITSourceCode Tutorial.
Where we will learn Python the easiest way possible. Python is very easy to learn language and Python is Fun!
Snapshot of the MyFile.txt after appending:
The with statement
The with statement is used to execute a pair of statements with a block of code in between. It was introduced in Python 2.5 and is useful for manipulating files.
Syntax:
with open(<file name>, <access mode>) as <file-pointer>:
#statement suite
With statement provides a guarantee to close the file, even if the nested block exits unexpectedly.
It is always better to use with the statement when working with files, as it will automatically close the file if a break, return, or exception occurs, preventing corruption.
Example:
with open("MyFile.txt",'w') as file:
content1 = file.write("Python is FUN!!")
print(content1)
4. Reading Files
To read a file using a Python script, the Python read() method can be used. This method reads a string from the file, which can be in either text or binary format.
Syntax:
fileobject.read(<count>)
The count specifies the number of bytes to be read from the beginning of the file. If no count is specified, the file will be read until the end.
Example:
# open the MyFile.txt in read mode.
sample1 = open("MyFile.txt","r")
# stores all the data of the file into the variable content1
content1 = sample1 .read(10)
# prints the type of the data stored in the file
print(type(content1))
# prints the content of the file
print(content1)
# closes the opened file
sample1.close()
Output:
<class 'str'>
Welcome t
The code above uses the read() function to read the content of MyFile.txt. The count value passed to the function is ten, meaning it will read the first ten characters from the file.
If we use the code below, it will print everything that is in the file.
content1 = sample1.read()
print(content1)
Output:
Welcome to ITSourceCode Tutorial.
Where we will learn Python the easiest way possible. Python is very easy to learn language and Python is Fun!
Read Lines of the file
Python makes it easy to read files line by line using the readline() method. This method reads the lines of the file from the beginning, so if you use it twice, you’ll get the first two lines of the file.
Example 1: Reading lines using readline() function
# open the MyFile.txt in read mode.
sample1 = open("MyFile.txt","r")
# stores all the data of the file into the variable content
content1 = sample1 .readline()
content2 = sample1 .readline()
# prints the content of the file
print(content1)
print(content2)
# closes the opened file
sample1.close()
Output:
Welcome to ITSourceCode Tutorial.
Where we will learn Python the easiest way possible.
We used the readline() function twice, which is why two lines were read from the file.
Python also has a readlines() method, which is used for reading lines, and returns a list of lines until it reaches the end of the file.
Example 2: Reading lines using readlines() function
# open the MyFile.txt in read mode.
sample1 = open("MyFile.txt","r")
# stores all the data of the file into the variable content1
content1 = sample1 .readlines()
# prints the content of the file
print(content1)
# closes the opened file
sample1.close()
Output:
['Welcome to ITSourceCode Tutorial.\n', 'Where we will learn Python the easiest way possible. Python is very easy to learn language and Python is Fun!']
Create a New File
Using one of the following access modes with the function open() lets you create a new file.
x: It makes a new file with the name you gave it. It gives an error if a file with the same name already exists.
a: If a file with the specified name does not exist, a new file is created. If the file already exists, the content is appended to the file.
w: It makes a new file with the given name if no such file already exists. It replaces the existing file.
Example 1:
# Start reading the file MyFile.txt. error if the file doesn't exist.
sample1 = open("MyFile.txt","x")
print(sample1)
Output:
<_io.TextIOWrapper name='MyFile.txt' mode='x' encoding='cp1252'>
Different Types of Files in Python
Python can work with two types of files: normal text files and binary files (written in binary language, 0s, and 1s).
- Text files: In this type of file, each line of text is terminated with the new line character (‘\n’) by default.
- Binary files: This type of file is stored in machine-understandable binary language, with no terminator for a line.
File Handling Methods in Python
The file object can be used in many different ways. Some of them have already been shown above.
Here is a list of all the methods in text mode, each with a short description:
Method | Description |
---|---|
close() | Closes a file that was open. If the file is already closed, it does nothing. |
detach() | The underlying binary buffer is separated from the TextIOBase and returned. |
fileno() | Returns the file’s file descriptor, which is an integer number. |
flush() | The flush method clears the file stream’s write buffer. |
isatty() | Returns True if the file stream is interactive. |
read(n) | Reads from the file up to n characters. If it is negative or None, it reads until the end of the file. |
readable() | Returns True if you can read from the file stream. |
readline(n=-1) | Reads one line from the file and gives it back. If given, reads in at most n bytes. |
readlines(n=-1) | Reads the file and gives back a list of lines. If given, reads in at most n bytes or characters. |
seek(offset,from=SEEK_SET ) | Changes the position of the file to offset bytes, referring to from (start, current, end). |
seekable() | Returns True if the file stream can be accessed in any order. |
tell() | Returns an integer that shows where the file’s object is right now. |
truncate(size=None ) | Changes the size of the file stream to bytes. If the size is not given, the size will be changed to fit the current location. |
writable() | Returns True if you can write to the file stream. |
write(s) | Write method writes the string s to the file and then returns the number of characters written. |
writelines(lines) | Writes a list of lines to the file. |
Summary
This tutorial has discussed the file handling functions in Python, the different types of files, and file methods in Python. I really hope that reading this article will teach you something new.
And lastly, if you missed any of our other lessons, you can always look at our list of Python Tutorial Topics.
Also, if you want to learn more about machine learning, you can look at our Best Machine Learning Projects with Source Code.
The next post, “Python Exceptions Handling“, consists of a list of standard Exceptions in Python and the assertions in Python.
Python Module Python Exception Handling