Python File Management
Automating File Renaming and Moving in Python
To rename or move files automatically in Python, you can use the os and shutil modules. These modules allow you to interact with the file system to rename files, move files from one directory to another, and perform other file operations.
Steps to Rename or Move Files Automatically in Python:
- Use the os module for file renaming.
- Use the shutil module for moving files.
Renaming Files Using os.rename()
The os.rename() function is used to rename a file or move it to a different location. It takes two arguments:
- The current file path.
- The new file path (can include a new name or location).
Example: Renaming a File
import os
# Path of the file to be renamed
current_path = "old_file.txt"
new_path = "new_file.txt"
# Rename the file
try:
os.rename(current_path, new_path)
print(f"File renamed to {new_path}")
except FileNotFoundError:
print(f"The file {current_path} does not exist.")
except Exception as e:
print(f"Error occurred: {e}")
Explanation:
- os.rename() changes the name of old_file.txt to new_file.txt.
- If the file doesn't exist, a FileNotFoundError is caught.
Moving Files Using shutil.move()
The shutil.move() function is used to move a file from one location to another. It can also rename the file if the destination path includes a new filename.
Example: Moving a File
import shutil
# Paths
source = "old_file.txt"
destination = "new_folder/old_file.txt" # Move to a new folder
# Move the file
try:
shutil.move(source, destination)
print(f"File moved to {destination}")
except FileNotFoundError:
print(f"The file {source} does not exist.")
except Exception as e:
print(f"Error occurred: {e}")
Explanation:
- shutil.move() moves the file old_file.txt to the new_folder.
- If the file is already in the target directory or if there are permission issues, it will raise an exception.
Automating Renaming and Moving Files Based on Patterns
You might want to automate renaming or moving files based on certain patterns, such as changing the extension or organizing files by date.
Example: Automatically Renaming Files in a Directory
import os
# Directory containing files
directory = "my_folder"
# Iterate over the files in the directory
for filename in os.listdir(directory):
if filename.endswith(".txt"):
new_name = f"renamed_{filename}"
old_file = os.path.join(directory, filename)
new_file = os.path.join(directory, new_name)
# Rename the file
try:
os.rename(old_file, new_file)
print(f"Renamed {filename} to {new_name}")
except Exception as e:
print(f"Error renaming {filename}: {e}")
Explanation:
- os.listdir(directory) lists all the files in the specified directory.
- The script renames .txt files to have a prefix renamed_ for each file.
Example: Automatically Moving Files Based on Extension
import shutil
import os
# Directories
source_directory = "my_folder"
destination_directory = "sorted_folder"
# Create the destination folder if it doesn't exist
if not os.path.exists(destination_directory):
os.makedirs(destination_directory)
# Iterate over files in the source directory
for filename in os.listdir(source_directory):
if filename.endswith(".txt"): # Move only .txt files
source_path = os.path.join(source_directory, filename)
destination_path = os.path.join(destination_directory, filename)
# Move the file
try:
shutil.move(source_path, destination_path)
print(f"Moved {filename} to {destination_directory}")
except Exception as e:
print(f"Error moving {filename}: {e}")
Explanation:
- This script moves all .txt files from the source_directory to the destination_directory.
Renaming Files with Timestamp for Uniqueness
Sometimes, it is helpful to append a timestamp to a file name to avoid naming conflicts.
Example: Renaming Files with Timestamp
import os
import time
# Current file
current_file = "old_file.txt"
# Generate a new name with a timestamp
timestamp = time.strftime("%Y%m%d_%H%M%S")
new_file = f"file_{timestamp}.txt"
# Rename the file
try:
os.rename(current_file, new_file)
print(f"File renamed to {new_file}")
except Exception as e:
print(f"Error renaming file: {e}")
Explanation:
- This script renames the file old_file.txt by appending the current timestamp, making the filename unique.
Conclusion
- Renaming files can be easily done with os.rename().
- Moving files is accomplished using shutil.move().
- You can automate the process to rename or move files based on patterns like extensions, timestamps, or any custom rule.
- For handling directories, you can use os.makedirs() to create directories if they do not exist.