File Handling

Python File Handling Tutorial

Python provides built-in functions to read, write, and modify files easily. This tutorial covers file handling operations, including opening, reading, writing, and appending files, along with error handling techniques.


1. Opening a File in Python

In Python, the open() function is used to open a file. The syntax is:

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

Example: Opening a File in Read Mode

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

Always close the file using close() to free up system resources.


2. Writing to a File in Python

The 'w' mode overwrites the existing content, while 'a' mode appends to the file.

Example: Writing to a File

with open("sample.txt", "w") as file:
    file.write("Hello, Python!\n")
    file.write("This is a file handling tutorial.\n")

Using with open() automatically closes the file after writing.


Example: Appending to a File

with open("sample.txt", "a") as file:
    file.write("Appending new line.\n")

Use 'a' mode to add content without deleting existing data.


3. Reading from a File

Example: Read the Entire File

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

Example: Reading Line by Line

with open("sample.txt", "r") as file:
    for line in file:
        print(line.strip())  # strip() removes extra spaces and newlines

Example: Reading Specific Number of Characters

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

4. File Handling with Exception Handling

To prevent errors, wrap file operations in a try-except block.

try:
    with open("non_existent.txt", "r") as file:
        print(file.read())
except FileNotFoundError:
    print("Error: File not found!")

Best practice: Always handle file-related errors gracefully.


5. Working with Binary Files

Binary mode ('b') is used for images, PDFs, and audio/video files.

Example: Copy an Image File

with open("image.jpg", "rb") as source_file:
    with open("copy.jpg", "wb") as destination_file:
        destination_file.write(source_file.read())

Use 'rb' and 'wb' for handling non-text files.


6. Deleting a File

Use the os module to delete a file.

import os

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

Always check if the file exists before deleting it.


Conclusion

Python's file handling features allow reading, writing, appending, and managing files efficiently. Always use with open() for automatic resource management and handle errors using try-except blocks.

For hands-on learning, try creating a file-based project, such as a simple text editor or a log manager!

Share on Google Plus

About It E Research

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment