DEV Community

Cover image for Comprehensive Guide to File Handling in Python
Tapoban Ray
Tapoban Ray

Posted on

Comprehensive Guide to File Handling in Python

File handling is the process of storing, reading, and writing data to and from files permanently on a storage device, rather than just in a computer's memory.

In this tutorial, you are going to learn the following,

  1. Types of files that can be handled in Python.
  2. The modes of opening a file.
  3. Reading from a file.
  4. Writing to a file.
  5. Using tell() and seek() functions.

Types of data files:

  1. Text Files: Stores data in the same format as typed.
    1. Regular Text Files (.txt)
    2. Delimited Text File.
      1. Tab-Separated Values files (.txt or .csv)
      2. Comma-Separated Values files (.csv)
  2. Binary Files: Stores information in the form of a stream of bytes. Not a human-readable format.

Opening and Closing files in Python

fileObj = open("myfile.txt", mode="r")
fileObj.close()

# -------------------------- OR --------------------------- 

with open("myfile.txt", mode="r") as fileObj:
    data = fileObj.read()
    # Closes file automatically once you get out of this indentation
Enter fullscreen mode Exit fullscreen mode

When using filenames with path, you remember the following:

  • Always make the file path string a raw string. Using a raw string helps us in ensuring there is no special meaning attached to any character of our file path string.
fileObj = open(r"C:\Temp\data1.txt", mode="r") # Use prefix 'r'

# -------------------------- OR --------------------------- 

fileObj = open("C:\\Temp\\data1.txt", mode="r") # Or use double slashes
Enter fullscreen mode Exit fullscreen mode

Common modes of opening a file:

A file-mode governs the type of operations possible in the opened file.

Text File Mode Binary File Mode Description
'r' 'rb' READ ONLY.
File must exist already, or Python raises I/O error.
'w' 'wb' WRITE ONLY.
File is created if it does not already exist. If the file already exists with data, Python overwrites it.
'a' 'ab' APPEND.
File is created if it does not already exist.
If the file exists with data, Python retains the data, and new data will be appended to the end.
'r+' 'rb+' or 'r+b' READ AND WRITE.
Properties of READ ONLY mode are applied.
Both read and write operations can take place.
'w+' 'wb+' or 'w+b' WRITE AND READ
Properties of WRITE ONLY mode are applied.
Both read and write operations can take place.
'a+' 'ab+' or 'a+b APPEND AND READ
File must exist already, or Python raises I/O error.

Reading and Writing files in Python

Writing Text files:

write(str) method -> Writes a string of characters

fileObj.write("Hello World")
Enter fullscreen mode Exit fullscreen mode

writelines([str]) method -> Writes a list of lines.

fileObj.writelines(["Hello 1", "World here"])
Enter fullscreen mode Exit fullscreen mode

Reading Text files:

  1. read(n) method -> Returns a Python String
data = fileObj.read()
# -------------------------- OR --------------------------- 
data = fileObj.read(n) # where n is the number of bytes to read.
Enter fullscreen mode Exit fullscreen mode
  1. readline(n) method -> Returns a line of string ending with '\n'
data = fileObj.readline()
# -------------------------- OR --------------------------- 
data = fileObj.readline(n) # where n is the number of lines to read.
Enter fullscreen mode Exit fullscreen mode
  1. readlines() method -> Returns a list of lines.
data = fileObj.readlines()
# -------------------------- OR --------------------------- 
data = fileObj.readlines() 
Enter fullscreen mode Exit fullscreen mode

Reading CSV files:

Opening CSV files with newline="" ensures that no translation of EndOfLine(EOL) character takes place.

import csv

fileObj = open("data.csv", mode="r", newline="")
cReader = csv.reader(fileObj)
for val in cReader:
    print(val)
Enter fullscreen mode Exit fullscreen mode

Writing CSV files:

import csv

fileObj = open("data.csv", mode="w", newline="")
cWriter = csv.writer(fileObj)
cWriter.writerow(["Roll No", "Name", "Marks"]) # Writes only one row

# Writes multiple rows at once.
cWriter.writerows(
    [
        ["01", "Raj", "50"],
        ["02", "Meera", "46"],
        ["03", "Anil", "48"],
    ]
)
fileObj.close()
Enter fullscreen mode Exit fullscreen mode

Writing Binary files:

import pickle

fileObj = open("data.dat", "wb")
data = {"Roll No": 1, "Name": "John", "Marks": 50}
pickle.dump(data, fileObj)
fileObj.close()
Enter fullscreen mode Exit fullscreen mode

Reading Binary files:

import pickle

fileObj = open("data.dat", "rb")
try: 
    while True:
        data = pickle.load(fileObj)
        print(data)

except EOFError:
    fileObj.close()
Enter fullscreen mode Exit fullscreen mode

The tell() function

Returns the current position of the file pointer in the file.

pos = fileObj.tell()
Enter fullscreen mode Exit fullscreen mode

The seek() function

Changes the position of the file-pointer by placing the file-pointer at the specified position of the opened file.

fileObj.seek(offset, mode)
Enter fullscreen mode Exit fullscreen mode

mode can be 0, 1, or 2.

  • 0 -> Move the file-pointer with respect to the beginning of the file. (DEFAULT MODE)
  • 1 -> Move the file-pointer with respect to the current position of the file.
  • 2 -> Move the file-pointer with respect to the end of the file.

seek() and tell() functions are mostly used when editing a file.

Top comments (0)