Home  >  Article  >  Backend Development  >  How to Rename Multiple Files in a Directory Using Python?

How to Rename Multiple Files in a Directory Using Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-23 17:51:46924browse

How to Rename Multiple Files in a Directory Using Python?

Renaming Multiple Files within a Directory Using Python

To rename multiple files within a directory using Python, consider utilizing the os.rename(src, dst) function, which facilitates renaming or moving files and directories. Here's an example code snippet:

<code class="python">import os

# Iterate through the files in the directory
for filename in os.listdir("."):
  # Check if the filename starts with "cheese_"
  if filename.startswith("cheese_"):
    # Rename the file by removing "cheese_"
    os.rename(filename, filename[7:])</code>

In this sample code, os.listdir(".") retrieves a list of files and directories in the current directory. The code then iterates through each filename and checks if it begins with "cheese_." If it does, the code uses os.rename(filename, filename[7:]) to change the filename to remove "cheese_".

By implementing this approach, you can efficiently rename numerous files in a directory according to your specified naming convention.

The above is the detailed content of How to Rename Multiple Files in a Directory Using Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn