Rename script with [Errno2] No such file or direct

2019-09-07 01:31发布

问题:

I have a folder with over 40 thousand images on an external drive, to use as a sequence for a timelapse. Before using ffmpeg though, I need to add trailing zeros to all the files. My attempt at a solution is shown below:

import os

path = '/Volumes/Arquivo\ \(carlosbgois@gmail.com\)/stadium_billiard/video/'
for filename in os.listdir(path):
    num = filename[:-4]
    num = num.zfill(4)
    new_filename = num + ".png"
    os.rename(os.path.join(path, filename), os.path.join(path, new_filename))

When running, I get the error [Errno2] No such file or directory on line 5. The files are named as 0.png, 1.png, ..., 32220.png, and so on. Any ideas on what may be causing this?

Have a nice day (:

回答1:

Figured out that when the path is given as a string, the backslashes preceding spaces and special characters are not needed, as they are in the terminal. Hence the working code is

import os

path = '/Volumes/Arquivo (carlosbgois@gmail.com)/stadium_billiard/video/'

for filename in os.listdir(path):
    num = filename[:-4]
    num = num.zfill(5)
    new_filename = num + ".png"
    os.rename(os.path.join(path, filename), os.path.join(path, new_filename))

Thanks!