Python 将数据框写入给定路径的excel文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38884164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
write dataframe to excel file at given path
提问by balakishore nadella
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()
I'm getting error : IOError: [Errno 22] invalid mode ('wb') or filename: 'C:\Users\Bala Nadella\output\temp-excel.xlsx'.
我收到错误:IOError:[Errno 22] 无效模式('wb')或文件名:'C:\Users\Bala Nadella\output\temp-excel.xlsx'。
How to create file in given path.
如何在给定路径中创建文件。
回答by Kartik
Study the table in that link. You need to escape your '\' with '\\'. Partly, DOS is responsible for this mess in the world.
研究该链接中的表格。您需要使用 '\\' 转义您的 '\'。部分原因是 DOS 造成了这个世界的混乱。
out_path = "C:\Users\Bala\output\temp-excel.xlsx"
Or
或者
out_path = r"C:\Users\Bala\output\temp-excel.xlsx" # the `r` prefix means raw string
But best alternative is this:
但最好的选择是这样的:
out_path = "C:/Users/Bala/output/temp-excel.xlsx"
It will work on any platform.
它适用于任何平台。
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.
编辑以删除解决方案os.path.abspath
。在这个答案下面的评论之后,我自己阅读了文档并意识到它有不同的目的。虽然我过去曾使用它使我的代码对双操作系统友好,因为它巧妙地将 CWD 附加到路径,并在从 Debian 移动到 Windows 时更改/
为\\
,反之亦然。
回答by user357269
In a string the backslash is an escape character. It means that you're giving a special command, not a regular character. Eg. "Hello\nWorld"
means, put a newline between "Hello"
and "World"
.
在字符串中,反斜杠是转义字符。这意味着您正在发出一个特殊命令,而不是常规字符。例如。"Hello\nWorld"
意味着,在"Hello"
和之间放置一个换行符"World"
。
If you actually want to use a backslash as a character, type it as "\\"
.
如果您确实想使用反斜杠作为字符,请将其键入为"\\"
.
Or better yet, just use forward slashes!
或者更好的是,只需使用正斜杠!