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

How to Rename Multiple Files in a Directory with Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-23 14:24:02304browse

How to Rename Multiple Files in a Directory with Python?

Renaming Multiple Files in a Directory using Python

In this question, the user seeks a solution to rename multiple files within a directory using Python. The specific requirement is to remove "CHEESE_" from the filename, leaving behind only "CHEESE_TYPE".

To achieve this, Python provides the os.rename() function to rename or move files or directories. The function takes two arguments:

os.rename(src, dst)

where src is the current filename, and dst is the new filename.

In the example provided by the user, the Python script loops through the files in the current directory using os.listdir(".") and renames any files that start with "cheese_" using the following code:

<code class="python">import os
for filename in os.listdir("."):
  if filename.startswith("cheese_"):
    os.rename(filename, filename[7:])</code>

This code successfully removes "CHEESE_" from the filenames, resulting in the following output:

$ ls
cheese_cheese_type.bar  cheese_cheese_type.foo
$ python
>>> import os
>>> for filename in os.listdir("."):
...  if filename.startswith("cheese_"):
...    os.rename(filename, filename[7:])
... 
>>> 
$ ls
cheese_type.bar  cheese_type.foo

The above is the detailed content of How to Rename Multiple Files in a Directory with 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