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

2024-10-02 04:20:57 发布

您现在位置:Python中文网/ 问答频道 /正文

这可以通过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

Tags: thepath方法代码inimport目录os
1条回答
网友
1楼 · 发布于 2024-10-02 04:20:57

你应该和os.walk()一起去。它将根据给定的目录参数映射目录树,并生成文件名

使用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))

相关问题 更多 >

    热门问题