首页  >  文章  >  后端开发  >  如何使用Python重命名目录中的多个文件?

如何使用Python重命名目录中的多个文件?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-23 17:51:46924浏览

How to Rename Multiple Files in a Directory Using Python?

使用 Python 重命名目录中的多个文件

要使用 Python 重命名目录中的多个文件,请考虑使用 os.rename(src , dst) 功能,方便重命名或移动文件和目录。下面是一个示例代码片段:

<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>

在此示例代码中,os.listdir(".") 检索当前目录中的文件和目录列表。然后,代码遍历每个文件名并检查它是否以“cheese_”开头。如果是这样,代码会使用 os.rename(filename, filename[7:]) 更改文件名以删除“cheese_”。

通过实现这种方法,您可以根据需要有效地重命名目录中的多个文件按照您指定的命名约定。

以上是如何使用Python重命名目录中的多个文件?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn