Python File Operations: Opening, Reading, Writing, and Directory Management
This guide explains how to open and close files, perform various read and write operations, and manage files and directories in Python using built‑in functions and the os, os.path, and shutil modules, with clear code examples for each task.
1. File Opening and Closing
Use the open function to obtain a file object. The basic syntax is file_object = open(file_name, mode), where file_name is the path and mode can be 'r' (read), 'w' (write), 'a' (append), 'b' (binary), or '+' (read/write) possibly combined.
file_object = open(file_name, mode)</code><code>file_name: path and name of the file</code><code>mode: file opening mode, e.g., 'r', 'w', 'a', 'rb', 'w+', etc.Close the file with the close method, or preferably use a with statement to ensure automatic closure even if an exception occurs.
file_object.close()</code><code>with open('example.txt', 'r') as file:</code><code> content = file.read()</code><code> print(content)2. File Read and Write Operations
Reading functions:
read(): read the entire file content</code><code>readline(): read a single line</code><code>readlines(): read all lines and return a listExamples:
# Read entire file</code><code>with open('example.txt', 'r') as file:</code><code> content = file.read()</code><code> print(content)</code><code># Read line by line</code><code>with open('example.txt', 'r') as file:</code><code> for line in file:</code><code> print(line.strip())</code><code># Read all lines into a list</code><code>with open('example.txt', 'r') as file:</code><code> lines = file.readlines()</code><code> print(lines)Writing functions:
write(): write a string to the file</code><code>writelines(): write a list of strings, each as a lineExamples:
# Write a single string</code><code>with open('example.txt', 'w') as file:</code><code> file.write("Hello, World!
")</code><code># Write multiple lines</code><code>lines = ["First line
", "Second line
", "Third line
"]</code><code>with open('example.txt', 'w') as file:</code><code> file.writelines(lines)3. File and Directory Operations
Creating directories with os.mkdir (single) or os.makedirs (nested):
import os</code><code># Create a single directory</code><code>os.mkdir('new_directory')</code><code># Create nested directories</code><code>os.makedirs('new_directory/sub_directory')Deleting directories with os.rmdir (empty) or shutil.rmtree (non‑empty):
import os</code><code>import shutil</code><code># Delete an empty directory</code><code>os.rmdir('new_directory')</code><code># Delete a non‑empty directory and its contents</code><code>shutil.rmtree('new_directory')Listing directory contents using os.listdir:
import os</code><code># List all entries in the current directory</code><code>entries = os.listdir('.')
print(entries)Getting file information with os.path utilities:
import os</code><code># Absolute path</code><code>file_path = os.path.abspath('example.txt')
print(file_path)</code><code># Existence check</code><code>exists = os.path.exists('example.txt')
print(exists)</code><code># File check</code><code>is_file = os.path.isfile('example.txt')
print(is_file)</code><code># Directory check</code><code>is_dir = os.path.isdir('new_directory')
print(is_dir)</code><code># File size</code><code>file_size = os.path.getsize('example.txt')
print(file_size)</code><code># Last modification time</code><code>last_modified = os.path.getmtime('example.txt')
print(last_modified)Moving or renaming files with shutil.move:
import shutil</code><code># Rename a file</code><code>shutil.move('old_name.txt', 'new_name.txt')</code><code># Move a file</code><code>shutil.move('source_directory/old_name.txt', 'destination_directory/new_name.txt')Copying files with shutil.copy or entire directory trees with shutil.copytree:
import shutil</code><code># Copy a single file</code><code>shutil.copy('source_file.txt', 'destination_file.txt')</code><code># Copy an entire directory tree</code><code>shutil.copytree('source_directory', 'destination_directory')Conclusion
The article provides a comprehensive overview of Python file handling, covering opening and closing files, reading and writing data, and performing common file system operations such as creating, deleting, listing, moving, and copying files and directories.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
