在 Python 中重命名目录中的多个文件 [英] Rename multiple files in a directory in Python

查看:18
本文介绍了在 Python 中重命名目录中的多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Python 重命名目录中的一些文件.

I'm trying to rename some files in a directory using Python.

假设我有一个名为 CHEESE_CHEESE_TYPE.*** 的文件并且想要删除 CHEESE_ 所以我得到的文件名将是 CHEESE_TYPE

Say I have a file called CHEESE_CHEESE_TYPE.*** and want to remove CHEESE_ so my resulting filename would be CHEESE_TYPE

我正在尝试使用 os.path.split 但它无法正常工作.我也考虑过使用字符串操作,但也没有成功.

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.

推荐答案

使用 os.rename(src, dst) 重命名或移动文件或目录.

Use os.rename(src, dst) to rename or move a file or a directory.

$ 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

这篇关于在 Python 中重命名目录中的多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆