编程目的
因需要大量重命名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
代码比较薄弱,仍需多加努力。—牵着蜗牛去爬山