python - os.rename 不起作用
问题描述
我尝试重命名文件。不希望文件以“__”开头。尝试使用帖子中的代码: 批量删除文件名中的字符
制作清单时:
myDir = os.listdir(r"S:\Shared\Santa Rosa")
for x in myDir:
...
我得到这个输出:
Tuesday
Wednesday
__1831.pdf
__1832.pdf
__1833.pdf
__1834.pdf
__1841.pdf
__1842.pdf
__1843.pdf
__1844.pdf
__1851.pdf
__1852.pdf
__1853.pdf
__1854.pdf
__1861.pdf
__1862.pdf
但是什么时候这样做:
for x in myDir:
os.rename(x, x.replace('__', ''))
我得到错误:
Traceback (most recent call last):
File "<interactive input>", line 2, in <module>
WindowsError: [Error 2] The system cannot find the file specified
解决方案
您应该为 os.rename 提供完整的路径名,例如
dirName = r"S:\Shared\Santa Rosa"
myDir = os.listdir(dirName)
for x in myDir:
oldName = os.path.join(dirName, x)
newName = os.path.join(dirName, x.replace('__', ''))
os.rename(oldName, newName)
推荐阅读
- android - CustomScope 可能不会引用具有不同范围的绑定
- android - 在 React Native 的标题中创建带有图像的导航抽屉
- arrays - 在 Go 中打印数组值
- laravel - Laravel Eloquent - 不检索所需的行
- php - 我在更新 MySQL 表行时遇到问题
- ios - IOS:以管理员身份运行 Rapidminer
- c# - 将图表导出到 Excel 文件
- php - PHP如何用空格替换字符串?
- list - 检查列表列表是否具有两个或多个相同的元素
- android - 警告:org.apache.poi.hssf.usermodel.DummyGraphics2d