Comprehensive Guide to File Operations in Python
Opening Files with the open() Function
To open a file in Python, use the open() functon, which returns a file object. Specify the file path and mode. Common modes include 'r' for reading, 'w' for writing (overwrites existing content), and 'a' for appending.
file_obj = open("example.txt", "w")
print("Mode:", file_obj.mode) # Outputs the access mode
print("Name:", file_obj.name) # Outputs the file name
print("Closed:", file_obj.closed) # Returns False if open
Output:
Mode: w
Name: example.txt
Closed: False
Key modes to remember: 'r', 'w', 'a+' (for reading and appending).
Reading Files: read(), readline(), and readlines()
Using read()
The read() method reads a specified number of characters from the file. If no argument is provided, it reads the entire file.
file_obj = open("example.txt", "r", encoding="utf-8")
content = file_obj.read(5) # Reads first 5 characters
print("Read content:", content)
file_obj.close()
Using readlines()
The readlines() method returns a list where each element is a line from the file, including newline characters.
file_obj = open("example.txt", "r", encoding="utf-8")
lines = file_obj.readlines()
print(lines)
file_obj.close()
Output example:
['Line 1\n', 'Line 2\n', 'Line 3']
Using readline()
The readline() method reads one line at a time, useful for large files to avoid high memory usage. Use a loop to read all lines.
file_obj = open("example.txt", "r", encoding="utf-8")
line = file_obj.readline()
while line:
print(line, end="")
line = file_obj.readline()
file_obj.close()
Writing Files with write()
The write() method writes a string to an open file. It does not automatically add a newline character.
file_obj = open("example.txt", "a", encoding="utf-8")
file_obj.write("Appended text")
file_obj.close()
Closing Files with close()
Always close files after operations to free resources. Use the close() method or the with statement for automatic closure.
# Manual closure
file_obj = open("example.txt", "r", encoding="utf-8")
for line in file_obj:
print(line, end="")
file_obj.close()
# Automatic closure with `with`
with open("example.txt", "r", encoding="utf-8") as file_obj:
for line in file_obj:
print(line, end="")
Renaming Files with os.rename()
Import the os module to rename files using os.rename(), which takes the old and new file paths.
import os
os.rename("old_name.txt", "new_name.txt")
Deleting Files with os.remove()
Use os.remove() from the os module to delete a file.
import os
os.remove("file_to_delete.txt")