本文翻译自:Rename multiple files in a directory in Python [duplicate]
This question already has an answer here: 这个问题在这里已有答案:
- How to rename a file using Python 10 answers 如何使用Python 10答案 重命名文件
- Rename multiple files in Python 5 answers 在Python 5答案中 重命名多个文件
I'm trying to rename some files in a directory using Python. 我正在尝试使用Python重命名目录中的一些文件。
Say I have a file called CHEESE_CHEESE_TYPE.***
and want to remove CHEESE_
so my resulting filename would be CHEESE_TYPE
假设我有一个名为CHEESE_CHEESE_TYPE.***
的文件,并且想删除CHEESE_
因此我的结果文件CHEESE_TYPE
I'm trying to use the os.path.split
but it's not working properly. 我正在尝试使用os.path.split
但它无法正常工作。 I have also considered using string manipulations, but have not been successful with that either. 我也考虑过使用字符串操作,但也没有成功。
#1楼
参考:https://stackoom.com/question/BZl5/在Python中重命名目录中的多个文件-重复
#2楼
此命令将在当前目录下的所有文件删除初始 “CHEESE_”的字符串,用重命名 :
$ renamer --find "/^CHEESE_/" *
#3楼
This sort of stuff is perfectly fitted for IPython, which has shell integration. 这种东西非常适合IPython,它具有shell集成。
In [1] files = !ls
In [2] for f in files:
newname = process_filename(f)
mv $f $newname
Note: to store this in a script, use the .ipy
extension, and prefix all shell commands with !
注意:要将其存储在脚本中,请使用.ipy
扩展名,并在所有shell命令前加上!
. 。
See also: http://ipython.org/ipython-doc/stable/interactive/shell.html 另见: http : //ipython.org/ipython-doc/stable/interactive/shell.html
#4楼
The following code should work. 以下代码应该有效。 It takes every filename in the current directory, if the filename contains the pattern CHEESE_CHEESE_
then it is renamed. 它接受当前目录中的每个文件名,如果文件名包含模式CHEESE_CHEESE_
,则重命名。 If not nothing is done to the filename. 如果没有对文件名做任何事情。
import os
for fileName in os.listdir("."):
os.rename(fileName, fileName.replace("CHEESE_CHEESE_", "CHEESE_"))
#5楼
Here is a more general solution: 这是一个更通用的解决方案:
This code can be used to remove any particular character or set of characters recursively from all filenames within a directory and replace them with any other character, set of characters or no character. 此代码可用于从目录中的所有文件名中递归删除任何特定字符或字符集,并将其替换为任何其他字符,字符集或无字符。
import os
paths = (os.path.join(root, filename)
for root, _, filenames in os.walk('C:\FolderName')
for filename in filenames)
for path in paths:
# the '#' in the example below will be replaced by the '-' in the filenames in the directory
newname = path.replace('#', '-')
if newname != path:
os.rename(path, newname)
#6楼
Here's a script based on your newest comment. 这是基于您最新评论的脚本。
#!/usr/bin/env python
from os import rename, listdir
badprefix = "cheese_"
fnames = listdir('.')
for fname in fnames:
if fname.startswith(badprefix*2):
rename(fname, fname.replace(badprefix, '', 1))