Reputation: 13
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()
Upvotes: 0
Views: 298
Reputation: 44283
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.
Upvotes: 2