0

I am not a programmer but I tried to automate renaming thousands of files using python. but this error appear. I've tried to shorten the path using win32api, using \\?\ notation before the path, even moving the folder to drive C:\ to shorten the path but the error still exist. I want the name of files to add 0 depending how many the files are. ex: if I have 2000 files, I want the name to be x0000,x0001, x0012, until the last x2000

import os, win32api

def main():
    i = 0
    path = "C:/New folder/"
    path = win32api.GetShortPathName(path)
    while i < len(os.listdir(path))+1:
        filename = os.listdir(path)
        s = len(str(i))
        p = "x" + ("0" * (4-int(s))) + str(i) + ".jpg"
        my_dest = p
        my_source = path + str(filename)
        my_dest =path + my_dest
        os.rename(my_source, my_dest)
        print(my_dest)
        i+=1

if __name__ == '__main__':
   main()
AO Jin
  • 13
  • 3

1 Answers1

2

os.listdir(path) returns a list of filenames, not a single filename. You must iterate over this list:

import os, win32api

def main():
    path = "C:/New folder/"
    path = win32api.GetShortPathName(path)
    filenames = os.listdir(path)
    for i, filename in enumerate(filenames):
        my_source = path + filename
        new_name = 'x%04d.jpg' % i
        my_dest = path + new_name
        os.rename(my_source, my_dest)
        print(my_source, my_dest) # print both

if __name__ == '__main__':
     main()

On one of my local directories I print (without renaming):

C:/Booboo/ANGULA~1/.htaccess C:/Booboo/ANGULA~1/x0000.jpg
C:/Booboo/ANGULA~1/angucomplete-alt C:/Booboo/ANGULA~1/x0001.jpg
C:/Booboo/ANGULA~1/angular-route.min.js C:/Booboo/ANGULA~1/x0002.jpg
C:/Booboo/ANGULA~1/angular.html C:/Booboo/ANGULA~1/x0003.jpg
C:/Booboo/ANGULA~1/angular2.html C:/Booboo/ANGULA~1/x0004.jpg
C:/Booboo/ANGULA~1/angular3.html C:/Booboo/ANGULA~1/x0005.jpg
C:/Booboo/ANGULA~1/angular4.html C:/Booboo/ANGULA~1/x0006.jpg
C:/Booboo/ANGULA~1/angular5.html C:/Booboo/ANGULA~1/x0007.jpg
C:/Booboo/ANGULA~1/angular6.html C:/Booboo/ANGULA~1/x0008.jpg
C:/Booboo/ANGULA~1/authorization.py C:/Booboo/ANGULA~1/x0009.jpg
C:/Booboo/ANGULA~1/authorization.pyc C:/Booboo/ANGULA~1/x0010.jpg
etc.
Booboo
  • 38,656
  • 3
  • 37
  • 60
  • ok, that's explain things. also what does this code mean? 'x%04d.jpg' % i – AO Jin Oct 16 '20 at 13:14
  • `%` in one context is the remainder operator (for example 7 % 2 == 1). But in this context being applied against a string it is the [String Formatting Operator](https://python-reference.readthedocs.io/en/latest/docs/str/formatting.html). In this case the value of `i` is being substituted in the string expression `'x%04d.jpg'` replacing `%04d`. `%04d` says that the `%` string formatting operator should expect an integer argument and should replace this format specification padded with zeroes so that the total length is 4. – Booboo Oct 16 '20 at 13:40