python中如何批量修改文件后缀名

需求背景

win10中的锁屏壁纸着实好看,想着能不能在本机中找到壁纸存放的目录,于是网上搜了一下,还真有。

壁纸文件存放的目录是

1
C:\Users\18856\AppData\Local\Packages\MicrosoftWindowsContentDeliveryManager_cw5n1h2txyewy\LocalState\Assets

上面18856是我电脑上的账户名,只需要修改为你自己的账户名即可,其它的所有分级目录都相同。

切换到噶目录下后,发现所有文件都没有后缀名,不能直接用图片查看器打开,需要一个个修改后缀名为.jpg格式,但是手工是在是太麻烦,因此想着用Python批量修改。

实现

os.path里面几个常用的API可以实现需求。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import os
import sys

path_input = sys.argv[1]
ext_input = sys.argv[2]

components = path_input.split('\\')
path_new = ''

# 将原始单斜杠'\'转为双斜杠'\\'
for idx, item in enumerate(components):
if idx != (len(components) - 1):
path_new += item + '\\\\'
else:
path_new += item

# print(path_new)

files = os.listdir(path_new)
for file in files:
# 分隔文件名和后缀名
fullname = os.path.splitext(file)
newname = fullname[0] + ext_input
os.rename(path_new + '\\\\' + file, path_new + '\\\\' + newname)

运行
从命令行中运行,需要附带两个参数:

  1. 原文件所在的目录,将windows中文件资源管理器上的路径拷贝过来;
  2. 目标后缀名,如.jpg

运行示例

1
2
python batch_rename.py C:\Users\18856\AppData\Local\Packages\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\LocalState\As
sets .jpg

参考文章

Donate comment here