Search code examples
pythonrenamelistdir

os.rename fail with [Errno 2] No such file or directory


using os.rename in python and getting '[Errno 2] No such file or directory'

full code:

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

Solution

  • listdir returns a list of files without the path

    So, you should do:

    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
    

    We use os.path.join to join the path to the filename.