在给定路径下将数据帧写入excel文件 [英] write dataframe to excel file at given path

查看:71
本文介绍了在给定路径下将数据帧写入excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I have a dataframe 
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})

This is working :
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()

but when I try 
out_path = "C:\Users\Bala\output\temp-excel.xlsx"
writer = pd.ExcelWriter(out_path , engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()

我遇到错误:IOError:[Errno 22]无效模式('wb')或文件名:'C:\ Users \ Bala Nadella \ output \ temp-excel.xlsx'.

I'm getting error : IOError: [Errno 22] invalid mode ('wb') or filename: 'C:\Users\Bala Nadella\output\temp-excel.xlsx'.

如何在给定路径中创建文件.

How to create file in given path.

推荐答案

字符串文字

研究该链接中的表格.您需要使用"\\"对您的"\"进行转义. DOS一定程度上是造成世界混乱的原因.

Study the table in that link. You need to escape your '\' with '\\'. Partly, DOS is responsible for this mess in the world.

out_path = "C:\\Users\\Bala\\output\\temp-excel.xlsx"

out_path = r"C:\Users\Bala\output\temp-excel.xlsx" # the `r` prefix means raw string

但这是最好的选择:

out_path = "C:/Users/Bala/output/temp-excel.xlsx"

它将在任何平台上运行.

It will work on any platform.

已编辑以使用os.path.abspath删除解决方案.在此答案下方的评论之后,我自己阅读了文档,并意识到它的用途有所不同.尽管我过去使用它来使我的代码对OS友好,因为它巧妙地将CWD附加到路径中,并且在从Debian移至Windows时将/更改为\\,反之亦然.

Edited to remove the solution with os.path.abspath. After the comment below this answer, I read the documentation myself and realized that it has a different purpose. Although I have used it in the past to make my code dual OS friendly, because it neatly appends CWD to the path, and changes / to \\ when moving from Debian to Windows and vice versa.

这篇关于在给定路径下将数据帧写入excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆