python - 使用 os.walk() 重命名文件夹和文件名
问题描述
我有一个文件夹,它本身有几个文件夹和文件,文件夹名称或文件名中带有字符“~”。我需要替换或删除文件夹名和文件名中的字符“~”。
import os
paths = (os.path.join(root, filename)
for root, _, filenames in os.walk('x:\\')
for filename in filenames)
# The keys of the dictionary are the values to replace, each corresponding
# item is the string to replace it with
replacements = {'~': ''}
for path in paths:
# Copy the path name to apply changes (if any) to
newname = path
# Loop over the dictionary elements, applying the replacements
for k, v in replacements.items():
newname = newname.replace(k, v)
if newname != path:
os.rename(path, newname)
我希望上面的代码可以重命名,但它说:“找不到路径”假设我有这个路径:“x:\ajaxgo~1.com\ajax\libs\jquery\110.2\jquery~1.js”pythonscript 会正确重命名所有内容并像这样生成它 "x:\ajaxgo1.com\ajax\libs\jquery\110.2\jquery1.js" 但 os.rename() 失败并且找不到路径。
解决方案
推荐阅读
- java - 我应该使用什么数据存储来在我的应用程序中存储歌词?
- javascript - Firefox 忽略 SVG 中的内联 CSS,chrome 显示它
- ruby-on-rails - 如何在 Rails 模型中导致关联回调
- grails - Grails:如何覆盖生成的服务方法?
- node.js - PSQL/Knex Insert or update on table violates foreign key constraint
- python - How to get the best model after early stopping without saving it to a file?
- laravel - Getting attributes of every json instance from an API
- python - 如何为 Tkinter 条目制作不可更改的默认文本?
- multithreading - Why do we use dynamic memory in ccNUMA systems when we talk about data distribution into locality domains by first touch policy?
- python - 如何在 Python 中每小时重新运行一个程序(同时执行多个任务)?