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'.
How can I create a file at a given path?
Use pandas to_excel() function to write a DataFrame to an excel sheet with extension . xlsx. By default it writes a single DataFrame to an excel file, you can also write multiple sheets by using an ExcelWriter object with a target file name, and sheet name to write to.
Algorithm: Create the DataFrame. Determine the name of the Excel file. Call to_excel() function with the file name to export the DataFrame.
You just specify the path as a string argument in save, as you do. The above saves a workbook. xls file in “/tmp” directory on my machine. So the full path is “/tmp/workbook.
For example, we can save the dataframe as excel file without index using “index=False” as additional argument. One of the common uses in excel file is naming the excel sheet. We can name the sheet using “sheet_name” argument as shown below.
String literals
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"
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.
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"
.
If you actually want to use a backslash as a character, type it as "\\"
.
Or better yet, just use forward slashes!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With