Skip to main content

File Handling in Python

Hey there! In this guide, we'll explore File Handling in Python. It covers the essentials of file handling in Python—from opening and closing files to reading, writing, and managing errors. Let's dive in!


File Handling in Python

File handling in Python allows programs to create, read, write, update, and manage files stored on a computer. It is an essential concept used in applications such as:

  • Saving user data
  • Reading configuration files
  • Processing logs
  • Working with CSV or text files
  • Storing reports and outputs

Python provides built-in functions and methods that make file handling simple and efficient.


1. Introduction to Files

A file is a collection of data stored permanently on a storage device.

Examples:

  • notes.txt
  • data.csv
  • report.pdf

Python mainly works with:

  • Text files (.txt, .csv, .json)
  • Binary files (.jpg, .png, .exe)

2. Opening a File

Python uses the open() function to work with files.

Syntax:

file_object = open(file_name, mode)

Parameters:

ParameterDescription
file_nameName or path of the file
modeSpecifies how the file will be used

3. File Modes

ModeDescription
rRead mode
wWrite mode (overwrites file)
aAppend mode
xCreate new file
bBinary mode
tText mode
r+Read and write

4. Reading Files

4.1 Reading Entire File

Example:

file = open("sample.txt", "r")
content = file.read()
print(content)
file.close()

Explanation:

  • open("sample.txt", "r") opens the file in read mode.
  • read() reads the entire file content.
  • close() closes the file.

4.2 Reading Line by Line

Example:

file = open("sample.txt", "r")

for line in file:
print(line)

file.close()

Explanation:

  • The loop reads one line at a time.
  • Useful for large files.

4.3 Using readline()

Example:

file = open("sample.txt", "r")

print(file.readline())
print(file.readline())

file.close()

Explanation:

  • readline() reads one line at a time.
  • Each call moves to the next line.

5. Writing to Files

5.1 Write Mode (w)

Example:

file = open("sample.txt", "w")
file.write("Hello, Python!\n")
file.write("File handling example.")
file.close()

Explanation:

  • w mode creates the file if it does not exist.
  • If the file already exists, its contents are overwritten.

5.2 Append Mode (a)

Example:

file = open("sample.txt", "a")
file.write("\nNew line added.")
file.close()

Explanation:

  • a mode adds content to the end of the file.
  • Existing data is preserved.

6. Creating a New File

Example:

file = open("newfile.txt", "x")
file.close()

Explanation:

  • Creates a new file.
  • Gives an error if the file already exists.

7. Closing Files

Closing a file:

  • Saves changes properly
  • Frees system resources
  • Prevents file corruption

Example:

file = open("sample.txt", "r")
print(file.read())
file.close()

8. Using with Statement

The with statement automatically closes files.

Syntax:

with open(file_name, mode) as file:
# file operations

Example:

with open("sample.txt", "r") as file:
content = file.read()
print(content)

Explanation:

  • No need to call close() manually.
  • Recommended approach for file handling.

9. Working with File Paths

9.1 Relative Path

open("data.txt", "r")

Uses a file from the current folder.


9.2 Absolute Path

open("C:/Users/Student/Documents/data.txt", "r")

Uses the full file location.


10. File Methods

MethodDescription
read()Reads entire file
readline()Reads one line
readlines()Reads all lines into a list
write()Writes content
close()Closes the file
seek()Moves file cursor
tell()Returns cursor position

11. Using seek() and tell()

Example:

file = open("sample.txt", "r")

print(file.tell())

file.read(5)

print(file.tell())

file.seek(0)

print(file.tell())

file.close()

Explanation:

  • tell() returns the current cursor position.
  • seek() moves the cursor to a specific position.

12. Reading Binary Files

Binary files store non-text data.

Example:

file = open("image.jpg", "rb")
data = file.read()
file.close()

Explanation:

  • rb means read binary mode.
  • Used for images, audio, videos, etc.

13. Writing Binary Files

Example:

file = open("copy.jpg", "wb")
file.write(data)
file.close()

Explanation:

  • wb means write binary mode.
  • Used to save binary data.

14. Exception Handling in File Operations

File operations may cause errors.

Examples:

  • File not found
  • Permission denied
  • Invalid file path

14.1 Example Using try-except

try:
file = open("missing.txt", "r")
print(file.read())
file.close()

except FileNotFoundError:
print("File does not exist.")

Explanation:

  • Prevents program crashes.
  • Handles file-related errors safely.

15. Example Program

Copy Content from One File to Another

with open("source.txt", "r") as source:
content = source.read()

with open("destination.txt", "w") as destination:
destination.write(content)

print("File copied successfully.")

Explanation:

  • Opens source file in read mode.
  • Reads content.
  • Opens destination file in write mode.
  • Writes content into new file.

16. Common File Handling Operations

TaskMode/Method
Read filer
Write filew
Append contenta
Create filex
Read binary filerb
Write binary filewb

17. Best Practices

  • Always close files after use.
  • Prefer with open() whenever possible.
  • Use exception handling.
  • Avoid overwriting important files accidentally.
  • Use meaningful file names.