本文翻譯自: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))