我很难使用os.rename批量重命名文件

2024-06-07 17:57:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码:

import os

videos = {}
subtitles = {}

files = [f for f in os.listdir('.') if os.path.isfile(f)]
for file in files:
 if (file[-3:] == "ass" or file[-3:] == "srt"):
  episode = file.split('#')[1].split(' ')[0]
  subtitles[episode] = file

 if (file[-3:] == "mp4"):
  episode = str(int(file.split('ep')[1].split('.')[0]))
  videos[episode] = file


i = 1
for sub in subtitles:
 try:
  extension = str(subtitles.get(str(i)))[-3:]
  video = str(videos.get(str(i))).split('.')[0]+"."+extension
  subtitle =  str(subtitles.get(str(i)))
  print (subtitle + video)
  os.rename(subtitle, video) # <---- 
  i+= 1
 except Exception as e:
  print ("Error: " + sub + " exception: " + str(e))

如果我注释行“os.rename(subtitle,video)”,只留下print命令,它会正常打印所有文件名,但是如果我不注释它,所有文件名都会变成“None”,每个文件都会出现以下错误:

NoneNone.one
Error: 99 exception: [WinError 2] The system cannot find the file specified: 'None' -> 'None.one'

Tags: innoneforgetifosvideovideos

热门问题