I'm trying to rename some files in a directory using Python.
Say I have a file called CHEESE_CHEESE_TYPE.***
and want to remove CHEESE_
so my resulting filename would be CHEESE_TYPE
I'm trying to use the os.path.split
but it's not working properly. I have also considered using string manipulations, but have not been successful with that either.
Answers
You can use the os
module to rename files in a directory by leveraging string manipulation. Here's a step-by-step guide on how to achieve this:
Example Code
import os
# Specify the directory containing the files
directory = '/path/to/your/directory'
# Iterate over all files in the directory
for filename in os.listdir(directory):
# Check if the file name starts with 'CHEESE_'
if filename.startswith('CHEESE_'):
# Remove 'CHEESE_' from the filename
new_filename = filename.replace('CHEESE_', '', 1) # Replace only the first occurrence
# Create full path for old and new file names
old_file = os.path.join(directory, filename)
new_file = os.path.join(directory, new_filename)
# Rename the file
os.rename(old_file, new_file)
print(f'Renamed: {old_file} to {new_file}')
Explanation
- Directory Path: Set the
directory
variable to the path where your files are located. - Iterate Over Files: Use
os.listdir(directory)
to get a list of files in the directory. - Check File Name: Use
startswith('CHEESE_')
to find files that start with the specified prefix. - Rename: Use
replace('CHEESE_', '', 1)
to remove the prefix from the filename. The1
ensures that only the first occurrence is replaced. - Full Paths: Use
os.path.join(directory, filename)
to get the full path for both the old and new filenames. - Rename File: Use
os.rename(old_file, new_file)
to rename the file.
Important Notes
- Make sure to adjust the
directory
variable to point to your specific directory. - Be careful when renaming files, especially in production environments, as this will change the actual file names.