2

在 python 中使用 os.rename 并得到 '[Errno 2] No such file or directory'

完整代码:

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
4

1 回答 1

3

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用来加入文件名的路径。

于 2017-05-26T14:15:36.450 回答