DerrickCrash
DerrickCrash

Reputation: 3

Pandas df.to.csv saves in the same working directory as opposed to absolute path

I have two scripts, both parse dataframes to csv files, one saves in ~/Desktop the other one in my current working directory, I need it to save to ~/Desktop

summary_file = local_file + ".csv"
series_file = local_file + ".csv"

print("this is the summary to %s" % summary_file)
file = open(summary_file, 'w')
file.write(breakdown)
file.close()

print("this is the full time series to %s" % series_file)
file = open(series_file, 'w')
file.write(df.to_csv())
file.close()

Until now I have tried: file.write(df.to_csv(r'/home//Desktop/')

The result was: file.close() ^ SyntaxError: invalid syntax

My OS is Ubuntu 21.04 and I am using Python3

Upvotes: 0

Views: 1683

Answers (1)

not_speshal
not_speshal

Reputation: 23156

You can directly write a pandas DataFrame to a csv by specifying the file with the full path. You don't have to use open except when you're writing strings.

Try:

#since breakdown is a string, use open()
with open(f"/home/username/Desktop/{summary_file}", "w") as f:
    f.write(breakdown) 

#since df is a DataFrame use to_csv()
df.to_csv(f"/home/username/Desktop/{series_file}")

Change the path as necessary.

Upvotes: 2

Related Questions