Python File Handling

Python File Handling

Python provides built-in functions to handle files, allowing you to read from, write to, and manipulate files stored on your system. File handling in Python is simple and intuitive, supporting various operations like opening, reading, writing, and closing files.

Opening a File

To open a file in Python, you use the open() function, which returns a file object. The open() function takes two main parameters:

  1. File name: The name of the file you want to open.
  2. Mode: Specifies the mode in which the file is opened.

File Opening Modes:

  • 'r' – Read (default): Opens the file for reading. Raises an error if the file doesn’t exist.
  • 'w' – Write: Opens the file for writing. Creates a new file if it doesn’t exist or truncates the file if it exists.
  • 'a' – Append: Opens the file for appending. Creates a new file if it doesn’t exist.
  • 'x' – Create: Creates a new file. Raises an error if the file already exists.

Additional modes:

  • 't' – Text mode (default): Opens the file in text mode.
  • 'b' – Binary mode: Opens the file in binary mode (e.g., images, videos).

Example 1: Opening a File in Read Mode

# Open file.txt for reading
file = open("file.txt", "r")

# Perform file operations (read, etc.)

# Close the file
file.close()

Writing and Reading Files

Writing to a File

To write data to a file, you can open it in 'w' (write) or 'a' (append) mode.

Example 2: Writing to a File

# Open file in write mode
file = open("file.txt", "w")

# Write some text to the file
file.write("Hello, this is a test file.\n")
file.write("Writing more content to the file.")

# Close the file after writing
file.close()

If the file already exists, the content will be overwritten. If it doesn’t exist, Python will create it.

Appending to a File

If you want to append data without overwriting the file, use the 'a' mode.

Example 3: Appending to a File

# Open file in append mode
file = open("file.txt", "a")

# Append text to the file
file.write("\nThis line is appended.")

# Close the file after appending
file.close()

Reading from a File

To read the content of a file, you open it in 'r' (read) mode and use various methods to read the data.

Methods for Reading Files:
  • read(size): Reads the entire file (or up to size number of characters if specified).
  • readline(): Reads a single line from the file.
  • readlines(): Reads all the lines of a file and returns them as a list.

Example 4: Reading from a File

# Open file in read mode
file = open("file.txt", "r")

# Read the entire content of the file
content = file.read()

print(content)

# Close the file after reading
file.close()

Example 5: Reading Line by Line

# Open file in read mode
file = open("file.txt", "r")

# Read file line by line
for line in file:
    print(line, end="")  # 'end=""' to avoid adding extra newline

# Close the file
file.close()

Using the with Statement

It’s a best practice to use the with statement when working with files. It automatically closes the file after the block of code is executed, even if exceptions occur.

Example 6: Using with for File Handling

with open("file.txt", "r") as file:
    content = file.read()
    print(content)
# No need to explicitly close the file

The with statement ensures that the file is closed properly, even in cases where exceptions occur.

File Methods

Here are some commonly used file methods:

  • write(string): Writes a string to the file.
  • read(size): Reads a specified number of characters from the file.
  • readline(): Reads a single line from the file.
  • readlines(): Returns all lines in a file as a list.
  • tell(): Returns the current position in the file.
  • seek(offset): Moves the file pointer to a specified position.

Example 7: Using tell() and seek()

with open("file.txt", "r") as file:
    # Read the first 5 characters
    print(file.read(5))
    
    # Get the current position
    position = file.tell()
    print(f"Current position: {position}")
    
    # Move the file pointer to the beginning of the file
    file.seek(0)
    
    # Read the entire file again
    print(file.read())

Output:

Hello
Current position: 5
Hello, this is a test file.
Writing more content to the file.
This line is appended.

Working with Binary Files

If you’re working with binary data, such as images, videos, or other non-text files, you need to open the file in binary mode using 'b'.

Example 8: Reading a Binary File

with open("image.jpg", "rb") as file:
    binary_data = file.read()
    print(binary_data)

Example 9: Writing to a Binary File

with open("image_copy.jpg", "wb") as file:
    file.write(binary_data)

Deleting a File

To delete a file, you can use the os.remove() function from the os module.

Example 10: Deleting a File

import os

# Delete file
os.remove("file.txt")

If you want to check whether a file exists before attempting to delete it, use os.path.exists().

if os.path.exists("file.txt"):
    os.remove("file.txt")
else:
    print("The file does not exist.")

File Handling Best Practices

  1. Always close the file: Use the with statement to ensure the file is properly closed after operations.
  2. Handle exceptions: When working with file I/O, use try-except blocks to handle potential errors (e.g., file not found, permission issues).
  3. Use binary mode for non-text files: Always open files in binary mode ('b') when dealing with images, videos, or other binary formats.

Summary

  • Python provides several built-in functions and methods for handling files.
  • You can open files in different modes ('r', 'w', 'a', etc.) to read, write, or append data.
  • Use the with statement to manage file resources efficiently.
  • There are different methods like read(), write(), readline(), and readlines() to interact with file content.
  • Python can also handle binary files (like images and videos) using 'b' mode.
Leave a Reply 0

Your email address will not be published. Required fields are marked *