如果不存在,如何创建Excel文件

时间:2019-07-03 20:30:14

标签: python-2.7

我正在尝试将标签添加到现有的excel文件中。如果文件不存在,我想创建一个。但是在我当前的程序中,我遇到了一个错误。

这是错误:FileNotFoundError:[Errno 2]没有这样的文件或目录

这是我的代码:

    book = load_workbook(out_path)
    writer = pd.ExcelWriter(out_path, engine='openpyxl')
    writer.book = book
    writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
    df.to_excel(writer,"Autocoded",index = False)
    writer.save()
    writer.close()

FileNotFoundError:[错误2]没有这样的文件或目录

1 个答案:

答案 0 :(得分:0)

    if os.path.isfile(out_path):
        book = load_workbook(out_path)
        writer = pd.ExcelWriter(out_path, engine='openpyxl')
        writer.book = book
        writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
        df.to_excel(writer,"Autocoded",index = False)
        writer.save()
        writer.close()
    else:
        df.to_excel(out_path)