Some text some message..
Back 16. File Operations in Python 25 Jun, 2025

Python provides built-in functions to handle files. The most common operations are:

1. Opening a File

Use the built-in open() function:

file = open('filename.txt', mode)
  • 'filename.txt' is the file name (and path if not in the current directory).

  • mode is the mode in which you open the file. Common modes:

    • 'r' — read (default)

    • 'w' — write (creates or truncates file)

    • 'a' — append (write data to the end)

    • 'b' — binary mode (used with other modes, like 'rb' or 'wb')

    • 'x' — create a new file and open it for writing (error if exists)

    • '+' — read and write (e.g., 'r+', 'w+')


2. Reading from a File

  • Read whole file:

file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()
  • Read line by line:

file = open('example.txt', 'r')
for line in file:
    print(line.strip())  # strip removes trailing newline
file.close()
  • Read a single line:

file = open('example.txt', 'r')
line = file.readline()
print(line)
file.close()
  • Read lines as list:

file = open('example.txt', 'r')
lines = file.readlines()
print(lines)
file.close()

3. Writing to a File

  • Overwrite or create file and write:

file = open('example.txt', 'w')
file.write("Hello, world!\n")
file.write("Welcome to file operations in Python.\n")
file.close()
  • Append to a file:

file = open('example.txt', 'a')
file.write("This will be added at the end.\n")
file.close()

4. Closing a File

After file operations, always close the file to free resources:

file.close()

5. Using with Statement (Recommended)

Using with automatically closes the file when the block is exited, even if an error occurs.

with open('example.txt', 'r') as file:
    content = file.read()
    print(content)
# No need to call file.close()

6. Other Useful File Operations

  • Check if file exists:

import os
if os.path.exists('example.txt'):
    print("File exists")
else:
    print("File does not exist")
  • Rename or delete file:

import os
os.rename('old.txt', 'new.txt')
os.remove('example.txt')

Summary Table of Modes

Mode Description
'r' Read (default)
'w' Write (overwrite or create)
'a' Append to file
'x' Create new file (fail if exists)
'b' Binary mode
'+' Read and write