python - 如何在 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")
解决方案
您已经有了一个方便的文件名列表,因此无需再次创建它。这是我的做法:
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))
推荐阅读
- javascript - 迷你 javascript 电子表格系统中“with”的替代方案
- db2 - 将 X 天添加到接收日期,但从日期表中排除周末/节假日
- r - 如何根据列的值订购 ggplot 热图?
- ruby-on-rails - Rspec parallel_test 控制器规范随机失败
- python - 如何阅读“abc.csv”,如果不存在阅读“xyz.csv”,使用熊猫?
- html - 将 Passport.js 和 Mongo 与我的 html 网站链接
- https - 只有 http:// 和 www url 不会重定向到 https
- javascript - 如何过滤英国邮政编码
- dart - Flutter 检查滚动的能力
- ruby-on-rails - 避免 n+1 has_many 孩子应该记住 parent