can't change filenames with os.rename because [Errno 2] No such file or directory

I have several filenames that are named like numbers like: 201810160820. I want to change the name to date + time, so the file will be renamed to: 16/10/2018 08:20.

I wrote the following code:

import os


for name in os.listdir('.'):
    newname = name[len(name)-6:len(name)-4]+'/'+name[len(name)-8:len(name)-6]+'/'+name[len(name)-12:len(name)-8]+' '+name[len(name)-4:len(name)-2]+':'+name[len(name)-2:len(name)]    
    os.rename(name, newname)

I gets an error: [Errno 2] No such file or directory I write this code on python 2.7 with kali linux. the files are existing and I can change the file name if I don't do a loop. where is the problem?

1 answer

  • answered 2018-12-05 20:03 blhsing

    os.listdir() returns just the names of the files, without the path names. You should use os.path.join to join the directory name with the file names in order for os.rename to locate them:

    dir = '.'
    for name in os.listdir(dir):
        newname = name[len(name)-6:len(name)-4]+'-'+name[len(name)-8:len(name)-6]+'-'+name[len(name)-12:len(name)-8]+' '+name[len(name)-4:len(name)-2]+'-'+name[len(name)-2:len(name)]    
        os.rename(os.path.join(dir, name), newname)

    Note that file names cannot contain '/' or ':', so you should use something like - as a delimiter instead.