在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
答案 0 :(得分:2)
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
加入文件名的路径。