In this python tutorial, you’ll understand all about python file handling with real-world examples. So, let’s get started.

Introduction to File Handling in Python

Before moving into how to handle files, we must have a basic idea about files itself.

A file is an object on a computer that stores data, information, settings, or commands which are used with a computer program. Files are used to store our data.

File handling refers to the operations that we perform on those files.

In Python file handling, we can create, read, update and delete files. So, let’s go through this Python tutorial and learn how to do all these operations one by one.

Python File Handling: Operations on file

How to open a file a file in python?

The key function used for working with files in Python, is the open() function.

Syntax – open(filename, mode)

There are four different methods (modes) for opening a file:

r – It is used for opening a pre-existing file for reading.

a – It opens a file in append mode and creates a new file in case if it doesn’t exist.

w – It opens a file for writing. It overwrites in case the file already exists and creates a new file otherwise.

x – It creates the specified file and returns an error if the file exists.

How to create a text file in python?

To create a text file in python, we can open a file with ‘a’ mode or ‘w’ mode.

file = open('test1.txt', 'a')
file = open('test2.txt', 'w')

How to read a file line by line in python?

# a file named "test", will be opened with the reading mode.
file = open('test.txt', 'r')
# This will print every line one by one in the file
for each in file:
  print (each)

How to read all lines in a file at once?

We use readlines() to read all the lines at a single time and return them as each line a string element in a list. This function is mostly used for small files in file handling, as it reads the whole file content to the memory, then splits it into separate lines.

Syntax – filename.readlines()

Code example – 

# a file named "test1", will be opened with the reading mode.
file = open('test1.txt', 'r')
# This will print all lines in the file at once
print (file.readlines())

How to read a csv file in python?

A CSV file (Comma Separated Values file) is a type of plain text file that uses specific structuring to arrange tabular data.

To read a CSV file, we use the CSV module.

Syntax –

with open(filename, ‘r’) as csvfile:

csvreader = csv.reader(csvfile)

Here, first, we open the CSV file in reading mode. The file object is named as CSV file. The file object is converted to a csv.reader object. And we save the csv.reader object as csvreader.

fields = csvreader.next()

csvreader is an iterable object. Hence, .next() method returns the current row and advances the iterator to the next row. Since the first row of our csv file contains the headers (or field names), we save them in a list called fields.

How to check if file or Directory exists in python?

Python provides many functionalities and one among them is to check whether a file or directory exists or not. This can be using an in-built OS module.

OS module in Python, provides us the functions for interacting with the operating system. It comes under Python’s standard utility modules. It provides a portable way of using operating system dependent functionality. os.path module is a submodule of OS module in Python which is used for common path name manipulation.

How to check if a file exists in python?

We have os.path.isfile() method in Python, which is used to check whether the specified path is an existing regular file or not.

Syntax – os.path.isfile(path)
path- A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.

Code example –

# importing os module  
import os 
# Path 
path = 'D:/projects/TechLearn/test/sample1.txt'
# Check whether the  specified path is an existing file 
isFile = os.path.isfile(path) 
print(isFile)

This method returns a boolean value, True if the specified path is an existing regular file, otherwise it returns False.

How to check if a directory exists in python?

Similarly, we have os.path.isdir() method in Python file handling, which is used to check whether the specified path is an existing directory or not.

Syntax – os.path.isdir(path)

path: A path-like object representing a file system path.

Code example – 

# importing os module  
import os 
# Path 
path = 'D:/projects/TechLearn/test/'
# Check whether the  specified path is an existing Directory
isDir = os.path.isdir(path) 
print(isDir)

This method returns True if the specified path is an existing directory, otherwise returns False.

Check if either a file or directory exists?

In the os module, we also have os.path.exists() method in Python that is used to check whether the specified path exists or not. This method can be used to check existence for both, file and directory.

Syntax – os.path.exists(path)

path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.

Code example –

# importing os module  
import os 
# File Path 
path = 'D:/projects/TechLearn/test/sample1.txt'
# Check whether the  specified path is an existing file 
isFile = os.path.exists(path) 
print(isFile)
# Directory Path 
path = 'D:/projects/TechLearn/test/'
# Check whether the  specified path is an existing Directory
isDir = os.path.exists(path) 
print(isDir)

This method returns a Boolean value of class bool. This method returns True if path exists otherwise returns False.

How to copy a file in Python?

Python file is copied by using shutil module.

The shutil module in Python provides us with many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules.

We can copy a file using the shutil library. So first we need to import it, using –

1. import shutilshutil.copyfile()

Syntax – shutil.copyfile(original, target)

original – here we need to send the path of the source file location

target – this is the destination path, the copied file can be found here

Code example –

# importing os module
import os
# importing shutil module
import shutil
# Source path
source = "/home/User/Documents/TechLearn/file.txt"
# Destination path
destination = "/home/User/Documents/TechLearn/file(copy).txt"
# Copy the content of source to destination
dest = shutil.copyfile(source, destination)
# Print path of newly created file
print("Destination path:", dest)

2. shutil.copystat()

shutil.copystat() method in Python is used to copy the permission bits, last access time, last modification time, and flags value from the given source path to the given destination path.

The shutil.copystat() method does not affect the file content and owner and group information.

Syntax: shutil.copystat(source, destination, *, follow_symlinks = True)

source: A string representing the path of the source file.

destination: A string representing the path of the destination file.

follow_symlinks (optional) : The default value of this parameter is True. If it is False and source and destination both refer to a symbolic link then the shutil.copystat() method will operate on the symbolic links themselves rather than the files the symbolic links refer to.

Python | shutil.copy() method

We also have another function which we can use to copy, that is, shutil.copy(). The main difference between shutil.copyfile() and shutil.copy() functions is that, shutil.copyfile() is used to make a copy of a file only, while, shutil.copy() can make a copy of a directory as well. Shutil.copy() behaves more like the Unix command cp (working for both files and directories).

Code example – 

# importing os module
import os
# importing shutil module
import shutil
# Source path
source = "/home/User/Documents/TechLearn/file.txt"
# Destination path
destination = "/home/User/Documents/Techlearn/file(copy).txt"
# Copy the content of source to destination
dest = shutil.copy(source, destination)

Python Rename File and Directory using os.rename()

In Python, the OS module provides functions for interacting with the operating system. It comes under Python’s standard utility modules.

os.rename() method in Python is used to rename a file or directory.

Syntax – os.rename(source, destination, *, src_dir_fd = None, dst_dir_fd = None)

source: path of the source file which is to be renamed.

destination: A path-like object representing the file system path.

src_dir_fd (optional): A file descriptor referring to a directory.

dst_dir_fd (optional): A file descriptor referring to a directory.

Code example – 

# importing os module
import os
# Source file path
source = 'TechLearn/file.txt'
# destination file path
dest = 'TechLearn/newfile.txt'
# Now rename the source to destination using os.rename() method
os.rename(source, dest)

Python ZIP file with example

A ZIP file is an archive file format that supports lossless data compression.

Extracting a zip file – To extract all the files from a zip file, we use the function extractall().

Code example –

# importing required modules
from zipfile import ZipFile
# specifying the zip file name
file = "my_files.zip"
# opening the zip file in READ mode
with ZipFile(file, 'r') as zip:
    # printing all the contents of the zip file
    zip.printdir()
    # extracting all the files
    print('Extracting the files...')
    zip.extractall()
    print('Done!!')

Python Exception Handling: Try, Catch, Finally

Error in Python can be of two types i.e. Syntax errors and Exceptions

Errors are the problems in a program due to which the program will stop the execution. 

What is an exception in python?

On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program.

In Python, Exceptions can be handled by try and except statements.

Code example – 

while True:
  user_input = input('Enter input')
  if user_input == 'exit':
    break
  try:
    num = int(user_input)
    print('It is an integer')
  except ValueError:
    print('Not an integer')

The try block lets you test a block of code for errors. The except block lets you handle the error. The finally block lets you execute code, regardless of the result of the try- and except blocks.

We can also define as many exception blocks as we want, for example, if we want to execute a special block of code for a special kind of error.

Code example – 

try:
  print(x)
except NameError:
  print("Variable x is not defined")
except:
  print("Something else went wrong")

We can also use the else keyword, to define a block of code to be executed if no errors are raised.

Code example – 

try:
  print("Hello")
except:
  print("Something went wrong")
else:
  print("Nothing went wrong")

The finally block, if specified, will be executed regardless if the try block raises an error or not.

Code example – 

try:
  print("TechLearn")
except:
  print("Something went wrong")
finally:
  print("But here we are...")

As a Python developer, we can choose to throw an exception, if a condition occurs. This must be either an exception instance or an exception class (a class that derives from Exception).

To throw (or raise) an exception, we use the raise keyword.

Code example –

x = 10
if x < 0:
  raise Exception("Sorry, no numbers below zero")

A complete python tutorial can be accessed here.

Explore Learning Paths at TechLearn

TechLearn Career path - Data Scientist
TechLearn career path - Python programmer
TechLearn career path - Deep Learning Engineer

Explore Live sessions at TechLearn –

Apple Siri - How Voice Recognition Work?
Apple Siri – How Voice Recognition Work?
How Tesla uses computer vision in autonomous cars
How Tesla uses computer vision in autonomous cars?
Netflix Recommendation system
Netflix Recommendation: How do they know what you like?

LEAVE A REPLY

Please enter your comment!
Please enter your name here