我正在尝试重命名我在文件夹中的多个mp3文件。他们从“1 Hotel California - The Eagles”等开始。我希望它只是“加州旅馆 - 老鹰队”。 此外,还有一个“05 Hotel California - The Eagles”,这意味着从不同的文件中删除数字会产生重复,这是我面临的问题。我希望它替换现有文件/覆盖/删除其中一个或任何解决方案。 P.S,将“3”添加到“1234567890”将从.mp3扩展名中删除“3”
我是python的新手,但这里是我用来实现这个
的代码 import os
def renamefiles():
list = os.listdir(r"E:\NEW")
print(list)
path = os.getcwd()
print(path)
os.chdir(r"E:\NEW")
for name in list:
os.rename(name, name.translate(None, "124567890 "))
os.chdir(path)
renamefiles()
这是我得到的错误 WindowsError:[错误183]当该文件已存在时无法创建文件
有关如何正确重命名文件的任何帮助都将非常感谢!
答案 0 :(得分:4)
您需要验证实际更改的名称是否已更改。如果名称中没有数字或空格,translate
将返回相同的字符串,您将尝试将name
重命名为name
,而Windows拒绝。尝试:
for name in list:
newname = name.translate(None, "124567890 ")
if name != newname:
os.rename(name, newname)
请注意,如果文件目标存在,这仍然会失败,如果您不小心将两个名称合并为一个,则可能需要这样做。但是如果您想要静默替换行为,如果您使用的是Python 3.3或更高版本,则可以将os.rename
更改为os.replace
以静默覆盖;在早期的Python上,您可以在调用os.remove
之前明确os.rename
。
答案 1 :(得分:2)
而不是使用name.translate,导入re lib(正则表达式)并使用类似
的内容"(?:\d*)?\s*(.+?).mp3"
作为你的模式。然后你可以使用
Match.group(1)
作为您的重命名。
为了处理多个文件,添加一个if语句,检查文件中是否已经存在这样的文件:
os.path.exists(dirpath)
其中dirpath是您要检入的目录
答案 2 :(得分:2)
您可以抓住OSError
并使用glob
查找.mp3文件:
import os
from glob import iglob
def renamefiles(pth):
os.chdir(pth)
for name in iglob("*.mp3"):
try:
os.rename(name, name.translate(None, "124567890").lstrip())
except OSError:
print("Caught error for {}".format(name))
# os.remove(name) ?
当您发现错误时,您所做的事情取决于您,您可以保留一些已找到的名称记录并增加每个名称的记录或保留原样。
如果数字始终在开头,你也可以稍微离开,这样你就可以安全地使用3:
os.rename(name, name.lstrip("0123456789 "))
使用您的一个示例字符串:
In [2]: "05 Hotel California - The Eagles.mp3".lstrip("01234567890 ")
Out[2]: 'Hotel California - The Eagles.mp3'
使用原始方法永远不会像删除所有空格那样正常工作:
In [3]: "05 Hotel California - The Eagles.mp3".translate(None,"0124567890 ")
Out[3]: 'HotelCalifornia-TheEagles.mp3'
如果您不关心哪个文件被覆盖,您可以使用shutil.move
:
import os
from glob import iglob
from shutil import move
def renamefiles(pth):
os.chdir(pth)
for name in iglob("*.mp3"):
move(name, name.translate(None, "124567890").lstrip())
另一方面,请勿使用list
作为变量名称。
答案 3 :(得分:2)
我无法轻易获得使用Python 3.5的任何答案,所以这里有一个在这种条件下工作:
import os
import re
def rename_files():
path = os.getcwd()
file_names = os.listdir(path)
for name in file_names:
os.rename(name, re.sub("[0-9](?!\d*$)", "", name))
rename_files()
这应该适用于像“1 Hotel California - The Eagles.mp3”这样的文件列表,将它们重命名为“Hotel California - The Eagles.mp3”(因此扩展名未被触及)。
答案 4 :(得分:0)
好的,你想要的是:
以下代码应该有效(未经过测试)。
import os
import string
class FileExists(Exception):
pass
def rename_files(path, ext, remove_existing=True):
for fname in os.listdir(path):
# test if the file name ends with the expected
# extension else skip it
if not fname.endswith(ext):
continue
# chdir is not a good idea, better to work
# with absolute path whenever possible
oldpath = os.path.join(path, fname)
# remove _leading_ digits then remove all whitespaces
newname = fname.lstrip(string.digits).strip()
newpath = os.path.join(path, newname)
# check if the file already exists
if os.path.exists(newpath):
if remove_existing:
# it exists and we were told to
# remove existing file:
os.remove(newpath)
else:
# it exists and we were told to
# NOT remove existing file:
raise FileExists(newpath)
# ok now we should be safe
os.rename(oldpath, newpath)
# only execute the function if we are called directly
# we dont want to do anything if we are just imported
# from the Python shell or another script or module
if __name__ == "__main__":
# exercice left to the reader:
# add command line options / arguments handling
# to specify the path to browse, the target
# extension and whether to remove existing files
# or not
rename_files(r"E:\NEW", ".mp3", True)
答案 5 :(得分:0)
您只需将目录更改为* .mp3文件所在的位置,并使用python执行以下2行:
import os,re
for filename in os.listdir():
os.rename(filename, filname.strip(re.search("[0-9]{2}", filename).group(0)))