Saturday, April 19.

File Handling in Python

File handling is an essential programming aspect, allowing us to read, write, and manipulate files. Python provides a simple and powerful way to handle files using built-in functions. In this article, we’ll explore various file-handling operations in Python.

file_handling_python_sainadh_reddy


1. Opening a File in Python

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

The basic syntax is: 

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

"filename.txt" is the name of the file. 
"mode" specifies how the file should be opened. 

File Opening Modes

.com/img/a/


2. Reading a File in Python

Reading the Entire File

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

This reads the entire file and prints its contents.

Reading Line by Line

with open("example.txt", "r") as file:
    for line in file:
        print(line.strip()) # Removes trailing newline characters


Reading Specific Number of Characters

with open("example.txt", "r") as file:
    content = file.read(10) # Reads first 10 characters
print(content)


Reading File as a List of Lines

with open("example.txt", "r") as file:
    lines = file.readlines()
print(lines)


This stores each line as an item in a list.


3. Writing to a File in Python

Overwriting a File (w mode)

with open("example.txt", "w") as file:
    file.write("Hello, this is a new file!\n")
    file.write("Overwriting existing content.")


Note: This mode erases the file’s existing content.

Appending Data (a mode)

with open("example.txt", "a") as file:
    file.write("\nAppending a new line.")


This adds content without deleting the existing data.


Writing Multiple Lines

lines = ["First line\n", "Second line\n", "Third line\n"]
with open("example.txt", "w") as file:
    file.writelines(lines)



4. Working with Binary Files

Binary files (e.g., images, videos, PDFs) require the "b" mode.

Reading a Binary File


with open("image.jpg", "rb") as file:
    data = file.read()
print(data) # Prints binary data


Writing a Binary File

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



5. Checking if a File Exists Before Opening

Use the os module to check if a file exists before reading or writing.

import os

if os.path.exists("example.txt"):
    with open("example.txt", "r") as file:
        print(file.read())
else:
    print("File not found!")



6. Deleting a File in Python

To remove a file, use os.remove().

import os

if os.path.exists("example.txt"):
    os.remove("example.txt")
    print("File deleted successfully.")
else:
    print("File does not exist.")



7. Exception Handling in File Operations

When working with files, it's good practice to handle exceptions to prevent crashes.

try:
    with open("example.txt", "r") as file:
        print(file.read())
except FileNotFoundError:
    print("Error: The file does not exist.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")



Python makes file handling easy with built-in functions like open(), read(), write(), and append(). By understanding different modes and handling exceptions, you can efficiently work with files in Python.