简体   繁体   English

如何在python中使用os.walk更改根文件夹和所有子目录中的ext?

[英]How do i use os.walk in python to change ext within root folder and all subdirectories?

greetings so i have a code that works for the root folder. 问候,所以我有一个适用于根文件夹的代码。

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")

then i attempt to use os.walk to iterate it though the sub folders and then it stops working in both the root folder or the sub folders here is the code: 然后我尝试使用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")

You have a handy list of filenames already, so no need to create it again. 您已经有了一个方便的文件名列表,因此无需再次创建它。 Here's how I'd do it: 这是我的处理方式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试对目录和子目录中的所有文件使用os.walk to和FreqDist - Trying to use os.walk to and FreqDist for all files in a directory and subdirectories 如何在Python中并行运行os.walk? - How do I run os.walk in parallel in Python? Python os.walk,使用子目录中的文件 - Python os.walk, working with files in subdirectories 如何使用os.walk从子目录中的文件访问信息? - how do I access information from files in subdirectories with os.walk? Python os.walk始终附加根目录 - Python os.walk always attaches root 我想使用 os.walk 迭代所有子目录,但只打印链接而不介入。如何降低复杂性? - I want to iterate all subdirectories using os.walk, but only print links without stepping in. How can I lower complexity? Os.walk 使用 python 从所有子目录中提取 .gz 文件 - Os.walk to exctract .gz files from all subdirectories using python 如何使用os.walk获得的Python中的natsort对文件夹名称进行排序? - How to sort folder names with natsort in Python that I got with os.walk? 在python中使用os.walk更改目录 - Change directory using os.walk in python 用os.walk()搜索所有excel文件,然后调用函数以读取此excel,我该怎么办? - seaching all excel files with os.walk (), then call the function to read this excel, How can I do it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM