Set File_Path for to_csv() in Pandas
Asked Answered
Z

4

16
funded=r'C:\Users\hill\Desktop\wheels\Leads(1).csv'
funded= read_csv(funded)
funded=DataFrame(funded)
path='C:\Users\hvill\Destop\ '
funded.to_csv(path,'greenl.csv')

I want to have a variable that I can set the path in to_csv to. I tried path_or_buf = path. That doesn't work either.

Zillion answered 4/4, 2014 at 21:2 Comment(0)
W
41

You need to either escape your back slashes or better use a raw string:

path='C:\\Users\\hvill\\Destop\\'

or better as fewer characters:

path=r'C:\Users\hvill\Destop\'

I also think you want to do this when saving:

funded.to_csv(path+'greenl.csv')

To avoid the ambiguity and allow portability of your code you can use this:

import os
funded.to_csv(os.path.join(path,r'green1.csv'))

this will append your csv name to your destination path correctly

Wildwood answered 4/4, 2014 at 21:5 Comment(1)
Just in case is of help to anybody, I construct a path concatenating strings and I wanted to add the r, so the result has been asada.to_csv(r"" + RESULTS_DIR + "viajes_withDIF_AUX_42.csv", ......Brahmi
P
3

It may just be the case that you missed the k out of desktop

Parfait answered 4/1, 2021 at 19:49 Comment(0)
N
0

When pandas.to_csv is called with two arguments, the first one means the file name to use (including any absolute or relative path). The second one means the text to use between cells in the output (CSV stands for "comma-separated values", but many programs that "read CSV files" can use different things besides commas, so Pandas gives the option to use something else).

Therefore, funded.to_csv(path,'greenl.csv') does not make any sense. The path is a folder name, not a file name, so Pandas cannot open it and write any data. If it could, it would try to use the text greenl.csv between every cell in the data (instead of a comma), which is clearly nonsense.

To solve the problem, create the full path and use that as the first argument, for example by using os.path.join, or using the pathlib.Path class to represent paths.

Nysa answered 10/4, 2023 at 3:13 Comment(0)
E
0

What worked for me is importing the pathlib library. This one has a better handling with windows paths.

import pathlib
import pandas as pd
df=pd.DataFrame('Your Data')


excel_file=pathlib.Path(r'C:\User\...','YourFileName.xlsx')
df.to_excel(excel_file,sheet_name='Sheet_Name', index='False')
Endodontist answered 22/4, 2024 at 21:15 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.