3

我正在尝试使用 Python 制作文件重命名器。我能够成功地从 Wikipedia 中获取剧集列表,但是在制作重命名文件时,我遇到了很多差异。我想要的是,我想使用与 if 条件匹配的扩展名,而不是最后的“.mkv”。有没有办法退货?

extensions = ('.webm','.mkv','.flv','.vob','.ogv', 
  '.ogg','.drc','.gif','.gifv','.mng','.avi','.mov', 
  '.qt','.wmv','.yuv','.rm','.rmvb','.asf','.amv','.mp4',
  '.m4p', '.m4v','.mpg', '.mp2', '.mpeg', '.mpe', '.mpv',
  '.mpg', '.mpeg', '.m2v','.m4v','.svi','.3gp','.3g2','.mxf',
  '.roq','.nsv','.f4v', '.f4p', '.f4a' ,'.f4b','.srt')
list = f.readlines()


y = 0
num = 1
for filename in os.listdir(path):
    if filename.endswith(extensions):
      os.rename(path+"\\"+filename,path+"\\"+str(num)+' - '+list[int(y)].strip('\n')+'.mkv') #instead of mkv, I want extension which was matched in the above if condition. 
    y += 1
    num += 1
4

3 回答 3

1

好吧,要么您必须逐个遍历扩展名,要么可以拆分文件名以获取扩展名。

按文件名拆分

for filename in os.listdir(path):
    if filename.endsswith(extensions):
        extension = filename.split('.')[-1] # you can use os.path.splitext too as Max Chretien suggested
        # ...

使用显式循环

for filename in os.listdir(path):
    matching_extensions = filter(lambda extension: filename.endswith(extension), extensions)
    if matching_extensions:
        extension = matching_extensions[0]
    # ...
于 2017-04-26T08:15:48.093 回答
1

另一个线索,首先我将提取filenamefile_extension使用os.path.splitext.

然后,如果file_extension匹配您的extensions元组,我将用 a 重命名它try except以查看是否有任何错误。

for file_path in os.listdir(path):
    filename, file_extension = os.path.splitext(file_path)
    if file_extension in extensions:
      try:
          os.rename(file_path, filename + '.mkv')
      except OSError:
          print("Error while renaming {}".format(filename))
于 2017-04-26T08:42:48.247 回答
0

如果我正确理解了您的问题,则以下代码可能会起作用。

extensions = ('.webm','.mkv','.flv','.vob','.ogv', 
  '.ogg','.drc','.gif','.gifv','.mng','.avi','.mov', 
  '.qt','.wmv','.yuv','.rm','.rmvb','.asf','.amv','.mp4',
  '.m4p', '.m4v','.mpg', '.mp2', '.mpeg', '.mpe', '.mpv',
  '.mpg', '.mpeg', '.m2v','.m4v','.svi','.3gp','.3g2','.mxf',
  '.roq','.nsv','.f4v', '.f4p', '.f4a' ,'.f4b','.srt')
list = f.readlines()


y = 0
num = 1
for filename in os.listdir(path):
    if ('.'+filename.lower().split('.')[1]) in list(extensions):
        os.rename(path+"\\"+filename,path+"\\"+str(num)+' - '+list[int(y)].strip('\n')+'.mkv')
    y += 1
    num += 1

我只是对你的代码做了一个小改动。

从:if filename.endswith(extensions):

至:if ('.'+filename.lower().split('.')[1]) in list(extensions):

希望能帮助到你!

于 2017-04-26T09:42:37.580 回答