将文件扩展名(如果是大写)更改为小写的最 Python 和最快的方法

  • 本文关键字:Python 方法 扩展名 文件 如果 python
  • 更新时间 :
  • 英文 :


我有一个文件列表,其中一些文件具有大写文件扩展名,例如file.PDF。在这些情况下,我想将大写更改为小写,例如文件.pdf

我想出了这个解决方案

currentDir = 'theDirectory'
for file in os.listdir(currentDir):
print(file)
if file[-3:] == 'PDF':
oldName = currentDir+'/'+file
newName = currentDir+'/'+file[:-3]+'pdf'
os.rename( oldName ,  newName )

我每天都要处理数百万个文件,所以重要的是它是最有效的方法。

有没有比上面的解决方案更好的方法?

这可能有效,使用 os.path.splitext()。

currentDir = 'theDirectory'
for file in os.listdir(currentDir):
print(file)
newExt=os.path.splitext(file)[1].lower()
oldName = currentDir+'/'+file
newName = os.path.splitext(file)[0]+newExt
os.rename( oldName ,  newName )

你也可以尝试在Python 3中使用pathlib

from pathlib import Path
dir_path = "C:/temp"
results = [x.rename(x.joinpath(x.parent,str(x.name).split(".")[0]+"."+str(x.name).split(".")[1].lower())) for x in Path(dir_path).iterdir() if x.is_file()]

希望对您有所帮助。

如果您想要小写所有扩展名,而不仅仅是"PDF",或者/并且对重命名有更多的控制权,最简单,直观和自描述的解决方案基础是

def lowercase_exts(folder):
for fname in os.listdir(folder):
name, ext = os.path.splitext(fname)
os.rename(os.path.join(folder, fname), os.path.join(folder, name + ext.lower()))

但是,如果您需要在Windows上有效地重命名数百万个pdf

import os
import subprocess
os.chdir(folder)
subprocess.call('ren *.PDF *.pdf', shell=True)

相关内容

最新更新