pandas to_csv – can’t save a named csv into a specific path

Trying the simple task of converting a df to a csv, then saving it locally to a specific path. I’ll censor the file name with “…” because I’m not sure about the privacy policy.

I checked many topics and I still run into errors, so I’ll detail all the steps I went through, with the output:

Attempt #1:

import pandas as pd

file_name = "https://raw.githubusercontent.com/.../titanic.csv"
df = pd.read_csv(file_name)

path = r'D:PROJECTSDATA_SCIENCEUDEMY_DataAnalysisBootcamp'
df.to_csv(path, 'myDataFrame.csv')

TypeError: “delimiter” must be a 1-character string

Attempt #2: After searching about “delimiter” issues, I discovered it was linked to the sep argument, so I used a solution from this link to set a proper separator and encoding.

import pandas as pd

file_name = "https://raw.githubusercontent.com/.../titanic.csv"
df = pd.read_csv(file_name)

path = r'D:PROJECTSDATA_SCIENCEUDEMY_DataAnalysisBootcamp'
df.to_csv(path, "myDataFrame.csv", sep=b't', encoding='utf-8')

TypeError: to_csv() got multiple values for argument ‘sep’

After playing with different arguments, it seems like my code use ‘myDataFrame.csv’ as the sep argument because when I remove it the code does not return error, but no file is create at the specified path, or anywhere (I checked the desktop, my documents, default “downloads” file).

I checked the documentation pandas.DataFrame.to_csv and I didn’t find a parameter that would allow me to set a specific name to the csv I want to locally create. I’ve been running in circles trying things that lead me to the same errors, without finding a way to save anything locally.

Even the simple code below does not create any csv, and I really don’t understand why:

import pandas as pd

file_name = "https://raw.githubusercontent.com/.../titanic.csv"
df = pd.read_csv(file_name)

df.to_csv("myDataFrame.csv")

I just want to simply save a dataframe into a csv, give it a name, and specify the path to where this csv is saved on my hard drive.

Answer

You receive the error because you are delivering to many values. The path and the file name must be provided in one string:

path = r'D:PROJECTSDATA_SCIENCEUDEMY_DataAnalysisBootcamp'

df.to_csv(path +'/myDataFrame.csv')

This saves your file at the path you like. However, the file of your last attempt should be saved at the root of your PYTHONPATH. Make sure to check on that. The file must exist.