Python File Operations

Python makes handling files straightforward and intuitive, allowing developers to perform basic and advanced file operations easily. This tutorial covers essential file operations including opening, reading, writing, appending, and managing files using Python.

1. Opening a File

Python uses the built-in open() function to handle file operations. The syntax for open() is:

file_object = open("filename", "mode")
  • filename: The name or path of the file you want to open.
  • mode: Specifies the mode in which the file is opened. Common modes include:
    • "r" – Read mode (default).
    • "w" – Write mode (creates a new file or overwrites an existing one).
    • "a" – Append mode (adds data to the end of the file).
    • "x" – Exclusive creation mode (creates a file only if it doesn’t exist).
    • "b" – Binary mode (e.g., "rb" for reading binary files).
    • "t" – Text mode (default; "rt" is explicitly text read mode).

Examples:

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

# Open a file for writing
file = open("example.txt", "w")

# Open a file for appending
file = open("example.txt", "a")

2. Reading Files

After opening a file in read mode, you can use methods like .read(), .readline(), and .readlines().

Example: example.txt contents:

Hello, world!
Welcome to Python file operations.
read()

Reads the entire file as a single string.

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

Output:

readline()

Reads one line at a time.

file = open("example.txt", "r")
line1 = file.readline()
line2 = file.readline()

print("Line 1:", line1)
print("Line 2:", line2)

file.close()

Output:

readlines()

Returns a list of lines.

file = open("example.txt", "r")
lines = file.readlines()

for line in lines:
    print(line, end="")

file.close()

3. Writing Files

Opening a file in write mode ("w") creates a new file or overwrites an existing one.

file = open("output.txt", "w")
file.write("Python file operations tutorial\n")
file.write("Writing to a file is easy.")
file.close()

output.txt now contains:

4. Appending Files

To add content to an existing file without overwriting, use append mode ("a").

file = open("output.txt", "a")
file.write("\nAppending additional content.")
file.close()

After appending, output.txt contents:

5. Using Context Managers (with)

Using the with statement ensures automatic closure of the file, even if an error occurs:

with open("example.txt", "r") as file:
    data = file.read()
    print(data)
# Automatically closed here

6. Binary Files

Python handles binary files, such as images or audio, by adding "b" to the file mode.

Example (reading binary files):

with open("image.png", "rb") as file:
    data = file.read()
    print(type(data))  # <class 'bytes'>

Example (writing binary files):

with open("output.bin", "wb") as file:
    file.write(b"\x00\xFF\x00\xFF")

7. Useful File Methods and Properties

Method / PropertyDescription
.nameReturns the name of the file
.modeReturns the mode the file is opened with
.closedReturns True if the file is closed
.seek(offset)Moves cursor position to specified offset
.tell()Returns the current position in the file

Example usage:

with open("example.txt", "r") as file:
    print(file.name)  # example.txt
    print(file.mode)  # r
    print(file.closed)  # False (file is open)

print(file.closed)  # True (file is now closed)

8. File Positioning (seek() and tell())

Python allows you to manipulate the cursor position within a file.

with open("example.txt", "r") as file:
    print(file.tell())  # Prints position: 0 (beginning)
    file.read(5)        # Reads 5 characters
    print(file.tell())  # Prints position: 5
    file.seek(0)        # Go back to the start
    print(file.tell())  # Prints position: 0

9. Handling Exceptions in File Operations

Always handle potential errors using exception handling (try-except) when dealing with file operations:

try:
    with open("nonexistent.txt", "r") as file:
        data = file.read()
except FileNotFoundError:
    print("File not found.")
except IOError:
    print("An error occurred during file operations.")

10. Deleting and Renaming Files

To delete or rename files, Python uses the os module:

Delete a file:

import os

if os.path.exists("output.txt"):
    os.remove("output.txt")
else:
    print("File doesn't exist!")

Rename a file:

import os

os.rename("old_file.txt", "new_file.txt")

Always remember:

  • Close files after operations or use context managers (with) to automatically close them.
  • Implement error handling for robust code.
  • Use the appropriate file modes to avoid data loss or corruption.

Leave a Comment

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

Scroll to Top