我需要重命名大约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'
有谁知道我哪里出错了?
编辑:
代码现在正在运作。
# 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()
答案 0 :(得分:1)
我认为你应该使用完整的路径:
filename = os.path.join("C:\path\to\Sales Packs", filename)
os.rename(filename, filename[0:11]+accName+".xlsx")