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

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

问题描述

假设我有一个名为 CHEESE_CHEESE_TYPE的文件。

/ code>并且想要移除 CHEESE _ ,所以我的结果文件名是 CHEESE_TYPE



我试图使用 os.path.split ,但是它不能正常工作。我也考虑过使用字符串操作,但还没有成功。

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

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


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

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

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.

解决方案

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天全站免登陆