Python 根据文件夹中已有的文件名重命名文件夹中的所有文件

Python 根据文件夹中已有的文件名重命名文件夹中的所有文件,python,operating-system,win32com,Python,Operating System,Win32com,我需要重命名大约2000个文件,因为它们当前在文件名的末尾有每个客户的帐号,但我被要求将其更改为帐户名 我可以通过从文件名末尾切片帐号并在Excel电子表格中查找来找到帐号,从而无任何问题地获得帐号 # open excel spreadsheet containing account names against numbers xl = Dispatch("Excel.Application") wb = xl.Workbooks.Add(r"C:\path\to\accountnumber

我需要重命名大约2000个文件,因为它们当前在文件名的末尾有每个客户的帐号,但我被要求将其更改为帐户名

我可以通过从文件名末尾切片帐号并在Excel电子表格中查找来找到帐号,从而无任何问题地获得帐号

# open excel spreadsheet containing account names against numbers

xl = Dispatch("Excel.Application")
wb = xl.Workbooks.Add(r"C:\path\to\accountnumbers.xlsx")
ws = wb.Worksheets(1)
row = 1
col = 1
empty = False

# get all the filenames of the files inside the sales pack folder

while not empty:
    val = ws.Cells(row,col).value
    val2 = ws.Cells(row,col+1).value
    for path, subdirs, files in os.walk(r"C:\path\to\Sales Packs"):
        for filename in files:
            accNo = filename[11:len(filename)-5]
            if accNo == val:
                accName = val2
                os.rename(filename, filename[0:11]+accName+".xlsx")  
    row += 1
    if val == None:
        empty = True

xl.Quit()
pythoncom.CoUninitialize()
当我运行此命令时,会出现以下错误:

Traceback (most recent call last):
  File "C:/Users/Ryan/Documents/filenamechange.py", line 29, in <module>
    os.rename(filename, filename[0:11]+accName+".xlsx")
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Sales_Pack_66 Books Ltd.xlsx'

我认为你应该使用完整的路径:

filename = os.path.join("C:\path\to\Sales Packs", filename)
os.rename(filename, filename[0:11]+accName+".xlsx")

或者干脆
os.path.join(path,filename)
。感谢您的回复-我收到了相同的错误消息,除了在文件名之前给出的路径。它在字母表中出现了“C”,但在此之前似乎已删除了所有文件。感谢您的帮助,我已对其进行了排序。我会用它来更新这个问题
filename = os.path.join("C:\path\to\Sales Packs", filename)
os.rename(filename, filename[0:11]+accName+".xlsx")