ValueError: rename: src too long for Windows on python

ValueError: rename: src too long for Windows on python

我不是程序员,但我尝试使用 python 自动重命名数千个文件。但出现此错误。我尝试使用 win32api 缩短路径,在路径前使用 \?\ 符号,甚至将文件夹移动到驱动器 C:\ 以缩短路径,但错误仍然存​​在。我希望文件名添加 0,具体取决于文件的数量。例如:如果我有 2000 个文件,我希望名称为 x0000、x0001、x0012,直到最后一个 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()

os.listdir(path) returns 文件名列表,而不是单个文件名。您必须遍历此列表:

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()

在我打印的一个本地目录中(不重命名):

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.