python - os.rename 失败并显示 [Errno 2] 没有这样的文件或目录

标签 python rename listdir

在 python 中使用 os.rename 并得到“[Errno 2]没有这样的文件或目录”

完整代码:

import os
from string import digits # digits are one of 0123456789

path = "/Users/xxx/Documents/version-control/secret-msg/prank/"
l = os.listdir(path) # returns list of files in folder
for o in l: #o for 'original'
    c = o.lstrip(digits) # c for 'clean', without leading digits; lstrip = left strip - so left strip any digit
    if (o != c):
        os.rename (o, c) #rename original filename to clean one
        print o + '-> ' + c # for debug only

最佳答案

listdir 返回不带路径的文件列表

所以,你应该这样做:

import os
import os.path
from string import digits # digits are one of 0123456789

path = "/Users/xxx/Documents/version-control/secret-msg/prank/"
l = os.listdir(path) # returns list of files in folder
for o in l: #o for 'original'
    c = o.lstrip(digits) # c for 'clean', without leading digits; lstrip = left strip - so left strip any digit
    if (o != c):
        os.rename (os.path.join(path, o),
                   os.path.join(path, c) #rename original filename to clean one
        print o + '-> ' + c # for debug only

我们使用 os.path.join 将路径连接到文件名。

关于python - os.rename 失败并显示 [Errno 2] 没有这样的文件或目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44203662/

相关文章:

powershell - 在Powershell中通过IP(不是主机名)重命名计算机

python - 查看文件夹内部

java - 从 python 中编译 java

python - 使用标准 django.contrib.auth.models.User 模型在 Sqlite 数据库中查询用户名 "x"的用户

linux - 如何在Linux中重命名列?

python - 如何用另一个数据框行重命名列名称?

python - 创建 View 中的表单是否已绑定(bind)?

python - 根据列值选择用户 - pandas dataframe

python - 在python中获取tgz文件的目录结构

python - 在python中重新排序文件名