首页 > 解决方案 > 如何在 python 中使用 os.walk 更改根文件夹和所有子目录中的 ext?

问题描述

问候,所以我有一个适用于根文件夹的代码。

import os, sys

path = 'root folder'

for filename in os.lestdir(os.path.dirname(path)):
    base_file, ext = os.path.splitext(filename)
    if ext == ".prn":
        os.rename(filename,base_file + "htm")

然后我尝试使用 os.walk 通过子文件夹对其进行迭代,然后它在根文件夹或子文件夹中都停止工作,这是代码:

import os, sys
path = 'root folder'
for roots, dirs, files in os.walk(path):
    for filename in os.lestdir(os.path.dirname(path)):
        base_file, ext = os.path.splitext(filename)
        if ext == ".prn":
            os.rename(filename,base_file + "htm")

标签: pythoniterationos.walk

解决方案


您已经有了一个方便的文件名列表,因此无需再次创建它。这是我的做法:

import os
path = 'root folder'
for subdir, dirs, files in os.walk(path):
    for filename in files:
        base_file, ext = os.path.splitext(filename)
        if ext == ".prn":
            new_name = base_file + '.htm'
            os.rename(os.path.join(subdir, filename),
                      os.path.join(subdir, new_name))

推荐阅读