Home > Blockchain >  How to export .csv file from python and using pandas DataFrame
How to export .csv file from python and using pandas DataFrame

Time:04-04

I am trying to export some filtered data from Python using Panda DF to .csv file (Personal Learning project)

Code : df5.to_csv(r'/C:/Users/j/Downloads/data1/export.csv')

Error: Traceback (most recent call last): File "C:\Users\jansa\PycharmProjects\bbb\main.py", line 62, in df5.to_csv(r'/C:/Users/jansa/Downloads/data1/export.csv')

File "C:\Users\jansa\PycharmProjects\bbb\venv\lib\site-packages\pandas\core\generic.py", line 3551, in to_csv

return DataFrameRenderer(formatter).to_csv(

File "C:\Users\jansa\PycharmProjects\bbb\venv\lib\site-packages\pandas\io\formats\format.py", line 1180, in to_csv csv_formatter.save()

File "C:\Users\jansa\PycharmProjects\bbb\venv\lib\site-packages\pandas\io\formats\csvs.py", line 241, in save with get_handle(

File "C:\Users\jansa\PycharmProjects\bbb\venv\lib\site-packages\pandas\io\common.py", line 697, in get_handle

check_parent_directory(str(handle))

File "C:\Users\jansa\PycharmProjects\bbb\venv\lib\site-packages\pandas\io\common.py", line 571, in check_parent_directory

raise OSError(rf"Cannot save file into a non-existent directory: '{parent}'")

OSError: Cannot save file into a non-existent directory: '\C:\Users\jansa\Downloads\data1'

I am researching, but cannot pinpoint the error.

CodePudding user response:

Try

df.to_csv(r'C:\path\to\directory\filename.csv')

CodePudding user response:

Generally, in Linux/Mac environment path separator is '/' but in windows, it is '\'. Also, the absolute path starts with '/' in Linux/Mac, while in windows, it starts with / So, using arguments in to_csv with C:\Users\j\Downloads\data1\export.csv' will resolve your issue.

In addition, if you want to get rid of such situations, you can do this:

import os
path = os.path.join('.', 'export.csv') #will save the file in current directory

Also, this returns the os path separator:

print(os.sep)
  • Related