代码之家  ›  专栏  ›  技术社区  ›  Rachel

使用函数将数据帧写入当前目录外的路径?

  •  2
  • Rachel  · 技术社区  · 8 年前

    我有一个问题与这个问题有关(可能是重复的) here .

    我尝试将pandas数据框写入给定路径中的Excel文件(以前不存在)。因为我必须做很多次,所以我尝试将其包装在函数中。以下是我所做的:

    df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
    
    def excel_to_path(frame, path):
        writer = pd.ExcelWriter(path , engine='xlsxwriter')
        frame.to_excel(writer, sheet_name='Output')
        writer.save()
    
    excel_to_path(df, "../foo/bar/myfile.xlsx")
    

    我被抛出错误 [Errno 2] No such file or directory: '../foo/bar/myfile.xlsx' . 怎么会这样?我该怎么解决?

    编辑 path 在当前工作目录中。但我想具体说明一下 路径 相反思想?

    1 回复  |  直到 8 年前
        1
  •  1
  •   thorbjornwolf    8 年前

    我通常会因为忘记创建目录而感到恼火。也许是这条路 ../foo/bar/ 还不存在?Pandas将为您创建文件,但不会创建父目录。

    具体来说,我猜您的设置如下所示:

    .
    └── src
        ├── foo
        │   └── bar
        └── your_script.py
    

    具有 src 作为你的工作目录 foo/bar 相对于您存在,但是 ../foo/bar 还没有!

    所以你应该添加 食物/酒吧 一级目录:

    .
    ├── foo_should_go_here
    │   └── bar_should_go_here
    └── src
        ├── foo
        │   └── bar
        └── your_script.py