[英]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.