File Handling in Python

📘 Python for Data Science 👁 53 views 📅 Nov 14, 2025
⏱ Estimated reading time: 3 min

File Handling in Python refers to the process of creating, reading, writing, and managing files using Python programs. It enables permanent data storage, as data stored in variables is temporary (lost when the program ends). Python provides built-in functions and methods to work with different types of files such as text, binary, and CSV files.

Python uses a simple and powerful interface for file operations through the built-in function open().


1. Opening a File

A file is opened using:

file = open("filename", "mode")

Common File Modes

ModeMeaning
'r'Read (default)
'w'Write (overwrites file)
'a'Append (adds data to end)
'b'Binary mode
't'Text mode (default)
'x'Create file (error if file exists)
'r+'Read and write

Example:

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

2. Reading from a File

Python provides several methods to read a file:

a) read()

Reads the entire file content.

f = open("data.txt", "r") content = f.read() print(content)

b) readline()

Reads one line at a time.

line = f.readline()

c) readlines()

Reads all lines into a list.

lines = f.readlines()

3. Writing to a File

a) write()

f = open("data.txt", "w") f.write("Hello Python")

b) writelines()

Writes a list of strings.

f.writelines(["Line1\n", "Line2\n"])

4. Closing a File

It is important to close a file to free system resources:

f.close()

5. Using with Statement (Best Method)

Using the with statement automatically closes the file after operations.

with open("data.txt", "r") as f: data = f.read() print(data)

Advantages:

  • No need to call close()

  • Automatically handles errors


6. File Handling for Binary Files

Used for images, videos, and audio.

with open("image.jpg", "rb") as f: data = f.read()

Writing binary files:

with open("copy.jpg", "wb") as f: f.write(data)

7. Important File Methods

MethodDescription
read()Reads entire file
readline()Reads one line
readlines()Reads all lines
write()Writes data
writelines()Writes list of strings
seek()Moves the cursor
tell()Returns current cursor position
close()Closes file

Example of seek():

f.seek(0) # Move cursor to beginning

8. Exception Handling in File Operations

File operations may cause errors (e.g., file not found). Use try-except:

try: f = open("abc.txt", "r") print(f.read()) except FileNotFoundError: print("File does not exist")

9. File Handling Applications

  • Logging

  • Storing user data

  • Reading configuration files

  • Processing big data files

  • Handling CSV files for data analysis


Conclusion

File Handling in Python provides a simple and powerful way to read, write, and manage files. Using the open() function, different modes, built-in methods, and exception handling, Python enables efficient processing of both text and binary files. The with statement makes file handling more reliable and professional. Understanding file handling is essential for real-world applications such as data processing, machine learning, and automation.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes