Openpyxl - 麻烦命名工作簿

时间:2015-05-07 17:17:15

标签: python xlsx openpyxl

我有一个python脚本,用于分析文件树并将其结果记录在xlsx中。

分析很顺利,但当我尝试录制结果时,我收到错误:

Traceback (most recent call last):
  File ".\call_validation.py", line 103, in <module>
    wb.save(wb_name)
  File "C:\Python\lib\site-packages\openpyxl\workbook\workbook.py", line 298, i
    save_workbook(self, filename)
  File "C:\Python\lib\site-packages\openpyxl\writer\excel.py", line 196, in sav
    writer.save(filename, as_template=as_template)
  File "C:\Python\lib\site-packages\openpyxl\writer\excel.py", line 178, in sav
    archive = ZipFile(filename, 'w', ZIP_DEFLATED)
  File "C:\Python\lib\zipfile.py", line 923, in __init__
    self.fp = io.open(file, modeDict[mode])
OSError: [Errno 22] Invalid argument: 'move_generated-2015-05-07 10:08:26.xlsx'

我正在使用datetime.datetime.now()生成我的文件名,如下所示:

save_time = str(datetime.datetime.now()).split(".")[0]
wb_name = "move_generated-" + save_time + ".xlsx"
wb.save(wb_name)

我不相信文件名太长,它只在C:\code\call_flow中,我试图从名称中删除所有非字母数字字符。有什么想法吗?

编辑:解决方案最终导致我未能剥离冒号。正如@nivix zixer所说,我通过替换

来修复它
save_time = str(datetime.datetime.now()).split(".")[0]

save_time = str(datetime.datetime.now()).split(".")[0].replace(':', '_')

1 个答案:

答案 0 :(得分:2)

也许问题是文件名中有空格?

str(datetime.datetime.now()).split(".")[0]替换为:str(datetime.datetime.now()).split(".")[0].replace(' ', '_')

很高兴我能帮助威尔!