Python File Handling Essential Tips and Tricks for Mastery

File Operation In Python

A file is a named position used for storing data. For example main.py is a file that is constantly used to store Python code.

Opening Files in Python Programming

In Python program, we need to open a file first to perform any operations on it—we use the open() function to do so. Let’s look at an example-

If we have a file named file1.txt.

Screenshot-2024-02-27-231633

Open this file, we can use the open() function.

file1 = open("file1.txt")

Below, we have maked a file object named file1. So, we can use this object to work with files.

Reading Files in Python Programming

Then we open a file, we can use the read() method to read its content. For example-

If we have a file named file1.txt.

Screenshot-2024-02-27-232037

So, let’s read the content of the file.

# open a file in read mode
file1 = open("file1.txt")

# read the file content
read_content = file1.read()
print(read_content)

Output:

This is a test file.
Hello from the test file.

In the upon example, the code file1.read() reads the extent of the file and stores it in the read_content variable.

Writing to Files in Python Program

For write to a Python file, we need to open it in write mode using the w parameter.

If we have a file named file2.txt. Let’s write to this file.

Screenshot-2024-02-28-001617

When we run the upon code, we will see the give out content inside the file.

Screenshot-2024-02-28-001816

Closing Files in Python Programming

When we are done causation operations on the file, we need to close the file rightly. We can use the close() function to close a file in Python. For example-

# open a file
file1 = open("file1.txt", "r")

# read the file
read_content = file1.read()
print(read_content)

# close the file
file1.close()

Output:

This is a test file.
Hello from the test file.

Opening a Python File Using with…open In python program

In Python program, there is a better avenue to open a file using with...open. For example-

with open("file1.txt", "r") as file1:
    read_content = file1.read()
    print(read_content)
``` program

We can get the present working directory using the getcwd() method of the os module.


**Output:**

```c
This is a test file.
Hello from the test file.

Below, with...open automatically closes the file, so that we don’t have to use the close() function.

Directory and Files Management In Python

A directory is a recruitment of files and subdirectories. A directory under a directory is known as a subdirectory.

Python has the os module that take steps us with many useful methods to work with directories (and files as well).

Get Current Directory in Python program

We can get the current working directory using the getcwd() method of the os module.

This method returns the present working directory in the form of a string. For example-

import os

print(os.getcwd())

# Output: C:\Program Files\PyScripter

Below, getcwd() returns the present directory in the form of a string.

Changing Directory in Python Programming

In Python program, we can change the present working directory by using the chdir() method.

The new path that we want to alternative into must be supplied as a string to this method. And we can use both the onwards-slash / or the backward-slash \ to individual the path elements.

Now let’s see an example-

import os

# change directory
os.chdir('C:\\Python33')

print(os.getcwd())

Output: C:\Python33

Below, we have used the chdir() method to change the present working directory and passed a new path as a string to chdir().

List Directories and Files in Python Programming

All files and sub-directories under a directory can be recover using the listdir() method.

This method receives in a path and returns a list of subdirectories and files in that path.

If no path is give out, it returns the list of subdirectories and files from the present working directory.

import os

print(os.getcwd())
C:\Python33

# list all sub-directories
os.listdir()
['DLLs',
'Doc',
'include',
'Lib',
'libs',
'LICENSE.txt',
'NEWS.txt',
'python.exe',
'pythonw.exe',
'README.txt',
'Scripts',
'tcl',
'Tools']

os.listdir('G:\\')
['$RECYCLE.BIN',
'Movies',
'Music',
'Photos',
'Series',
'System Volume Information']

Making a New Directory in Python Programming

In Python Program, we can make a new directory using the mkdir() method.

This method accepts in the path of the new directory. If the full path is not give off, the new directory is created in the present working directory.

os.mkdir('test')

os.listdir()
['test']

Renaming a Directory or a File In Python

The rename() method can be rename a directory or a file.

To renaming any directory or file, rename() takes in two basic contention:

  • the old name as the first contention
  • the new name as the second contention.

Now let’s see an example-

import os

os.listdir()
['test']

# rename a directory
os.rename('test','new_one')

os.listdir()
['new_one']

Below, 'test' directory is renamed to 'new_one' using the rename() method.

Removing Directory or File in Python

In Python Program, we can use the remove() method or the rmdir() method to remove a file or directory.

At First let’s use remove() to delete a file.

import os

# delete "myfile.txt" file
os.remove("myfile.txt")

There, we have used the remove() method for remove the "myfile.txt" file.

Let’s use rmdir() to delete an empty directory,

import os

# delete the empty directory "mydir"
os.rmdir("mydir") 

In order to remove non-empty directory, we can use the rmtree() method under the shutil module. For example-

import shutil

# delete "mydir" directory and all of its contents
shutil.rmtree("mydir")

It’s significant to note that these functions permanently delete the files or directories, so we need to gingerly when using them.

Exceptions In Python

An exception is an unexpected instance that arrive during program execution. For example,

divide_by_zero = 7 / 0

The upon code causes an exclusion as it is not possible to division a number by 0.

Logical Errors (Exceptions) In python

Errors that arrive at runtime (after passing the syntax test) are called exceptions or logical errors.

For example, they occur when we

  • try to open a file(for reading) that does not subsist (FileNotFoundError)
  • try to division a number by zero (ZeroDivisionError)
  • try to import a module that does not subsist (ImportError) and so on.

Now Let’s see at how Python treats these errors:

divide_numbers = 7 / 0
print(divide_numbers)

Output:

Traceback (most recent call last):
 File "<string>", line 1, in <module>
ZeroDivisionError: division by zero

Built-in Exceptions In Python

Illegal operations can increment exceptions. There are abundant of built-in exceptions in Python that are increment when corresponding errors occur.

We can spectacle all the built-in exceptions using the built-in local() function as follows:

print(dir(locals()['__builtins__']))

Below, locals()['__builtins__'] will come-back a module of built-in exceptions, functions, and attributes and dir accept us to list these attributes as strings.

Screenshot-2024-02-28-015432 Screenshot-2024-02-28-015528 Screenshot-2024-02-28-015620

Exception Handling In Python

While exceptions abnormally terminate the performance of a program, it is important to handle performance. In Python, we use the try...except block to handle exceptions.

Python try…except Block In Python program

The try...except block is used to handle exclusion in Python. Here’s the syntax of try...except block:

try:
    # code that may cause exception
except:
    # code to run when exception occurs

Below, we have installed the code that might produce an exception inside the try block. Each try block is followed by an except block.

When an exclusion occurs, it is caught by the except block. The except block cannot be used except the try block.

Example: Exception Handling Using try…except In Python

try:
    numerator = 10
    denominator = 0

    result = numerator/denominator

    print(result)
except:
    print("Error: Denominator cannot be 0.")

# Output: Error: Denominator cannot be 0. 

In the above example, we are trying to division a number by 0. There, this code produce an exception.

For handle the exception, we have put the code, result = numerator/denominator under the try block. Now when an exception happens, the rest of the code under the try block is skipped.

The except block catches the exclusion and statements under the except block are executed.

Catching Specific Exceptions in Python Programming

For every try block, there can be zero or over except blocks. poly-nominal except blocks allow us to handle each exception otherwise.

The argument type of every except block strike the type of exception that can be handled by it. Now For example-

try:
    
    even_numbers = [2,4,6,8]
    print(even_numbers[5])

except ZeroDivisionError:
    print("Denominator cannot be 0.")
    
except IndexError:
    print("Index Out of Bound.")

# Output: Index Out of Bound
Previous
Python Datatypes Mastering the Essentials - Complete Guide
Next
Python Flow Control: If-else and Loop with practical examples