Python: 遍历给定目录下的pdf文档并进行重命名

编程目的

因需要大量重命名pdf文档为[0…n].pdf,就搜集了资料写了代码,并解决自己的问题。

参考

感谢各位分享的资源。

python3.3 遍历文件夹及文件 小例
python文件重命名
一文看懂Python对文件和文件夹的操作: 含os, shutil和glob模块详解

代码(一)

import glob
import os.path

# 找到给定的root_dir下的pdf文档并重命名为 0.pdf ... n.pdf
# root directory the location you want to find pdf files
# user defined root_dir
# change root_dir according to your needs
root_dir = r'C:\Users\ECHO\Documents\test'

# find all the pdf file in the root_dir
pdfFiles = glob.glob(os.path.join(root_dir, '*.pdf'))

# renamed the pdf files with numbers
index = 0
for one_pdf in pdfFiles:
    print("Processing file: " + str(one_pdf))
    newName = str(index) + ".pdf"
    print(str(one_pdf), "---->", newName)
    os.rename(os.path.join(root_dir, str(one_pdf)), os.path.join(root_dir, newName))
    index += 1
    

代码(二)

import glob
import os.path

# 找到给定的root_dir下的pdf文档并重命名为 0.pdf ... n.pdf
# 该程序可找到root_dir子文件夹里的pdf文档并重命名为 0.pdf ... n.pdf

# user defined root_dir
# change root_dir according to your needs
root_dir = r'C:\Users\ECHO\Documents\test'

for parent, dir_names, file_names in os.walk(root_dir):
    for dir_name in dir_names:
        print("parent folder is:" + parent)
        print("dir_name is:" + dir_names)
        
    name_index = 100
    for filename in file_names:
        print("parent folder is:" + parent)
        # check whether this file is a pdf file
        **if filename.endswith('.pdf'):**
           print("filename with full path:" + os.path.join(parent, filename))
           # the following line is used to renamed the  files
           newName = str(name_index) + ".pdf"
           print(filename, "---->", newName)
           os.rename(os.path.join(parent, filename), os.path.join(parent, newName))
           name_index += 1


代码比较薄弱,仍需多加努力。—牵着蜗牛去爬山

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值