In Python, file manipulation is an essential aspect of working with files and directories. The os
and shutil
modules provide a variety of functions for performing operations like renaming, deleting, and manipulating files. In this article, we will explore how to handle file operations in Python with examples.
Renaming files is a simple operation that can be done using the os.rename()
function. This function allows you to change the name of a file or move it to a different location.
import os # Rename a file os.rename('old_file.txt', 'new_file.txt') print("File renamed successfully")
In this example, the file old_file.txt
is renamed to new_file.txt
. If the file exists and is accessible, the operation will be successful.
To delete a file in Python, the os.remove()
function can be used. This function removes the specified file from the filesystem.
import os # Delete a file os.remove('file_to_delete.txt') print("File deleted successfully")
In this example, the file file_to_delete.txt
is deleted. Make sure the file exists and is not in use before attempting to delete it.
Manipulating files involves various operations like reading from and writing to files. Below are examples of some common file manipulation tasks.
# Read the contents of a file with open('example.txt', 'r') as file: content = file.read() print(content)
In this example, the file example.txt
is opened in read mode, and its contents are read and printed to the console.
# Write to a file with open('output.txt', 'w') as file: file.write("Hello, this is a new file!\n") file.write("Python makes file manipulation easy.") print("File written successfully")
This example creates or overwrites the file output.txt
with the provided text. The w
mode opens the file for writing.
# Append text to a file with open('output.txt', 'a') as file: file.write("\nAppended text!") print("Text appended successfully")
This example appends text to the existing output.txt
file. The a
mode is used to open the file in append mode, ensuring that the new content is added at the end without overwriting the existing content.
import os # Check if a file exists if os.path.exists('file_to_check.txt'): print("File exists") else: print("File does not exist")
This example demonstrates how to check if a file exists using the os.path.exists()
function. It returns True
if the file exists and False
otherwise.
import os # Get file information file_info = os.stat('example.txt') print(f"File Size: {file_info.st_size} bytes") print(f"Last Modified: {file_info.st_mtime}")
In this example, the os.stat()
function is used to retrieve information about the file, such as its size and last modification time.
Python provides powerful tools for file manipulation, allowing you to rename, delete, and work with file contents with ease. The os
and shutil
modules are crucial for interacting with the file system. With these functions, you can automate tasks related to file handling, making your programs more efficient and flexible.