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

Write dataframe to path outside current directory with a function?

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

我尝试将 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'。怎么会这样,我该如何解决?

EDIT :只要定义的 path 在当前工作目录中,它就可以工作。但我想改为指定任何给定的 path。想法?

我常常因为忘记创建目录而犯错。也许路径 ../foo/bar/ 还不存在? Pandas 将为您创建文件,但不会创建父目录。

详细来说,我猜你的设置是这样的:

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

src 是您的工作目录,因此 foo/bar 相对于您存在,但 ../foo/bar 还不存在!

因此您应该将 foo/bar 目录添加到上一级:

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