How to Rename Multiple Files in a Directory with Python?

Mary-Kate Olsen
Release: 2024-10-23 14:24:02
Original
309 people have browsed it

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)
Copy after login

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>
Copy after login

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
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!