Question

I need to rename about 2000 files because they currently have the account number of each customer at the end of the file name, but I've been asked to change this to the account name.

I'm able to get the account name without any issue by slicing the account number from the end of the file name and looking it up in an Excel spreadsheet to find the account name.

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

When I run this I get the following error:

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'

Does anyone know where I'm going wrong?

EDIT:

The code is working now.

# 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
                filename = os.path.join(path, filename)
                os.rename(filename, path+r"\Sales Pack_"+accName+".xlsx")
    row += 1
    if val == None:
        empty = True

xl.Quit()
pythoncom.CoUninitialize()
Était-ce utile?

La solution

I think you should use the full path:

filename = os.path.join("C:\path\to\Sales Packs", filename)
os.rename(filename, filename[0:11]+accName+".xlsx")
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top