BloG

Understanding File Handling in Python, with Examples

Jan 13, 2023

In this text on handling files with Python, you’ll learn easy methods to use the Python OS module and easy methods to navigate through local files and directories. You’ll also learn easy methods to open, read, write and shut files in Python.

File handling is a great approach to persist data after a program terminates. Data from a pc program is saved to a file and could be accessed later. Python, like many other programming languages, provides handy methods to create, open, read and write data to a file.

Contents:

  1. File Handling in Python: Files and File Paths
  2. File Handling in Python: Reading and Writing Data

File Handling in Python: Files and File Paths

Files are quick alternatives for persisting data from a pc program. The random-access memory (RAM) can only store data temporarily, as all of the previous data is lost immediately after the pc system is turned off. Files are preferred, because they’re a more everlasting storage point for data on a pc. A file is a location on an area disk where data is stored. It has two essential properties: a filename, and its path.

Using the OS module

Python provides an inbuilt OS module for interacting with our computer’s operating system. The OS module has interfaces (functions) that help with performing operations like navigating through directories and files in Python, creating folders, identifying file paths, and so forth.

To make use of the OS module, we import it into our program as shown below:

import os

Find out how to get the present working directory

We will get the present working directory (“cwd”) in Python using the getcwd() method. This method returns the trail of the directory we’re currently working in as a string, as shown within the code snippet below:

import os

directory = os.getcwd()
print(directory)
>>>>
/home/ini/Dev/Tutorial/sitepoint

Absolute vs relative paths

File paths could be laid out in two ways: either by their absolute path, or by their relative path. Each paths point to the present file location.

The absolute path of a file declares its path, starting with the basis folder. An absolute path looks like this:

/home/ini/Dev/Tutorial/sitepoint/filehandling.py

The basis folder (as seen within the above code) is home on a Linux OS.

The relative path of a file declares its path in relation to the present working directory. Let’s see an example:

./sitepoint/filehandling.py

The code above shows the relative path for the Python file filehandling.py.

Find out how to create a directory in Python

The OS module has a mkdir() method for creating latest folders or directories in Python. The mkdir() method takes one argument — a reputation for the directory — to be created in the present directory as a default behavior. See the code below:

import os

os.mkdir(“photos”)

Nonetheless, we are able to create directories in a unique location by specifying the file path. Within the code example below, a projects folder is created within the Tutorial folder:

os.mkdir(“/home/ini/Dev/Tutorial/projects”)

Once we check contained in the Tutorial folder, we’ll find the newly created projects folder.

Find out how to change the present working directory

To modify between directories, use the chdir() method. The brand new path is passed in as an argument to the tactic to vary from the present working directory to a different one.

After making a latest folder within the previous code sample, we are able to change the directory to the projects folder:

import os

os.chdir(“/home/ini/Dev/Tutorial/projects”)

To verify the change within the directory, use the getcwd() method, which returns a string of the present working directory: /home/ini/Dev./Tutorial/projects.

Find out how to delete files or directories in Python

Files and directories could be deleted in Python using the OS module’s remove() and rmdir() methods respectively.

To delete files in Python, input the file path within the os.remove() method. When deleting files, if the file doesn’t exist, this system will throw the FileNotFoundError.

Let’s take a code example:

import os

os.remove(“random.txt”)

To delete or remove a directory, use os.rmdir(), passing within the directory path to be deleted, like so:

import os

os.rmdir(“/home/ini/Dev/Tutorial/projects”)

The projects folder is deleted from the Tutorial folder.

Find out how to list files and directories in Python

To get an summary of all of the content of a directory, use the os.listdir() method. This method returns a listing of all the present files and directories in that specific folder:

import os

print(os.listdir())
>>>>
[‘array.py’, ‘unittesting.py’, ‘search_replace.py’, ‘__pycache__’, ‘pangram.txt’, ‘.pytest_cache’, ‘exception.py’, ‘files.py’, ‘regex.py’, ‘filehandling.py’]

File Handling in Python: Reading and Writing Data

File handling in Python is easy and never as complicated as it will probably be in other programming languages. There are different file access modes to pick from when opening a Python file for any operation:

  • r: opens a file for reading. The read mode throws an error when the file doesn’t exist.

  • r+: opens the file to read and write data right into a file object. An error is thrown if the file doesn’t exist.

  • w: a file is opened on this mode for writing data. The write mode overrides existing data and creates a latest file object if it doesn’t exist.

  • w+: opens a file to read and write data. Existing data on file is overridden when opened on this mode.

  • a: the append mode appends to a file if the file exists. It also creates a latest file if there’s no existing file. It doesn’t override existing data.

  • a+: this mode opens a file for appending and reading data.

  • x: the create mode is used to create files in Python. An error is thrown if the file exists.

Adding b to any of the access modes changes it from the default text format to a binary format (for instance, rb, rb+, wb, and so forth).

Find out how to open a file in Python

To open a file in Python, the open() function is used. It takes not less than two arguments — the filename, and the mode description — and returns a file object. By default, a file is opened for reading in text mode, but we are able to specify if we wish the binary mode as a substitute.

An easy syntax to open a file looks like this:

f = open(‘filename’, ‘mode’)

After this step, as seen within the code above, we are able to begin our read–write operations on the file object. In default mode, files are all the time handled in text mode.

Find out how to close a file in Python

After a file object is opened and file processing operations are carried out, we close the file. It’s often the last step in reading or writing files in Python. The file object close() method is used to shut earlier opened files.

Closing files in Python looks like this:

f = open(‘filename’, ‘mode’)
// file operations, reading, writing or appending
f.close()

The with statement

It’s a normal practice to shut files after they’ve been opened and file operations have been carried out. It’s possible to miss out on closing some files after they’ve been opened.

The with statement routinely closes files after the last file handling operation is accomplished in its scope. For instance:

with open(‘random.txt’, ‘r’) as f:
print(f.read())
>>>>
Hello world!
Hello world!

As seen within the code snippet above, the with statement implicitly closes the file after the print statement.

Find out how to read a file in Python

There are a pair of how to read data from a file in Python. We will read a file’s contents using the read(), readline(), and readlines() methods.

The read() method

The read() method returns a string of all characters on the file being read. The pointer is placed initially of the file content. The default mode is to read from the start of the file to the top of the file, except where the variety of characters is specified.

Take a have a look at the code snippet below:

f = open(‘random.txt’, ‘r’)
print(f.read())
f.close()
>>>>
This is some random text.
Here is the second line.
The sky is blue.
Roses are red.

We will specify what number of characters to read from the text file. Simply pass the variety of characters as an argument to the read() method:

f = open(‘random.txt’, ‘r’)
print(f.read(12))
f.close()
>>>>
This is some

As seen in the instance above, the intepreter reads only twelve characters from the complete file.

The readline() method

This method reads one line from a file at a time. It reads from the start of the file and stops where a newline character is found. See the code example below:

f = open(‘random.txt’, ‘r’)
print(f.readline())
f.close()
>>>>
This is some random text.

The readlines() method

This method returns a listing of all lines from the present file being read. See the code snippet below:

f = open(‘random.txt’, ‘r’)
print(f.readlines())
f.close()
>>>>
[‘This is some random text.n’, ‘Here is the second line.n’, ‘The sky is blue.n’, ‘Roses are red.’]

Note: all of the methods for reading a file stream return an empty value when the top of the file is reached. The seek() method returns the file cursor to the start of the file.

Find out how to write to a file in Python

The write() method in Python is beneficial when attempting to jot down data to a file. To jot down to an opened file, the access mode needs to be set to certainly one of the next: w, w+, a, a+, and so forth. Once more, the default is text mode moderately than binary.

The write() method

Pass a string argument to this method when we wish to jot down data to a text file. Keep in mind that the write mode will override existing data if the file exists:

f = open(‘random.txt’, ‘w’)
f.write(“Hello world!”)
f.close()

The writelines() method

This method helps us insert several strings to a text file directly. We will write multiple lines of strings to a file in a single go by passing the list as an argument of the tactic:

words = [‘The sky is blue’, ‘nRoses are red’]

f = open(‘random.txt’, ‘w’)
f.writelines(words)
f.close()

The code above shows a closed file being opened and a few lines in a thesaurus being inserted directly into the random.txt text file.

Conclusion

There are two necessary attributes a couple of file: the filename and its path. The OS module helps us navigate through directories and perform certain operations. Python file handling involves using several methods to open, create, read, and write data on file objects.

It’s also necessary to know file handling in Python if we wish to interact with content inside text or binary files. At all times ensure to shut files after carrying out operations on them. The with statement makes it easier to perform file handling in Python, because it implicitly closes file objects after we’re done.

Related reading: