【问题标题】:Saving an excel file using pandas in a specific file使用 pandas 在特定文件中保存 excel 文件
【发布时间】:2022-10-14 23:04:43
【问题描述】:

我希望以 .xlsx 格式将 excel 文件存储到我称为数据的特定文件夹中。该文件与正在运行的程序位于同一文件夹中。

该程序每小时创建一个新的mydict,这就是为什么我在名称中使用它,以便以后可以处理它。

    import pandas as pd
    from pandas import ExcelWriter
    import datetime

    mydict = self._detailed_cost
    todays_date = str(datetime.datetime.now().strftime("%Y-%m-%d-%H%M"))

    df = pd.DataFrame.from_dict(mydict, orient='index')
    with ExcelWriter('data/' + todays_date + '-cost_function'+'.xlsx') as writer:
        df.to_excel(writer, 'costs', index=True)

运行此代码我收到以下错误:

OSError: Cannot save file into a non-existent directory: '..\data'

理想情况下,我不会给出绝对路径,因为我在一台 PC 上编码,我希望它在另一台具有不同路径的 PC 上运行。

【问题讨论】:

    标签: python excel pandas pandas.excelwriter


    【解决方案1】:
     with ExcelWriter(r'data/' + todays_date + '-cost_function'+'.xlsx') as writer:
          
    

    如上所述,在路径的开头使用r 来指示相对路径。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-10
      • 1970-01-01
      • 2021-09-28
      相关资源
      最近更新 更多