简体   繁体   中英

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM