包含子文件夹的文件夹,包含多个文件(.xlsm,.pdf,.txt)。如何将.pdf文件重命名为子文件夹'名称?

时间:2017-10-19 17:22:45

标签: python python-2.7 python-3.x

这可以用python完成,但我想我错过了循环所有目录的方法。这是我正在使用的代码:

import os
 def renameInDir(directory):  
    for filename in os.listdir(directory):
      if filename.endswith(".pdf"):
        path = os.path.realpath(filename)
        parents = path.split('/') //make an array of all the dirs in the path. 0 will be the original basefilename
        newFilename=os.path.dirname(filename)+directory +parents[-1:][0] //reorganize data into format you want 
        os.rename(filename, newFilename)//rename the file

1 个答案:

答案 0 :(得分:0)

你应该选择os.walk()。它将通过给定的目录param映射目录树,并生成文件名。

使用os.walk(),您将以这种方式完成所需的结果:

import os
from os.path import join
for dirpath, dirnames, filenames in os.walk('/path/to/directory'):
    for name in filenames:
        new_name = name[:-3] + 'new_file_extension'
        os.rename(join(dirpath, name), join(dirpath, new_name))