How to write dataframe to csv to the current working directory python

13.7k views Asked by At

My code would be something like this:

  import os
  import pandas as pd
  cwd = os.getcwd()
  csv_name = '/CONTCAR_SORTED'
  df = pd.read_csv(f"{cwd}{csv_name}",
                 skiprows=2, nrows=100, names=['X','Y','Z' ], 
                 delimiter='\s+',engine='python')

  df=df.to_csv("new")

In this way, the output file is written in the directory where the executed python script is located. I have tried different ways to specify a different folder but no file is written in those cases. I don't know how to pass and change to another path to the destination.

3

There are 3 answers

2
Stefan On BEST ANSWER
cwd = os.getcwd()
path = cwd + "/new"
df.to_csv(path)

Your file will be stored in the working directory with the name 'new'.

0
Ehsan Poursaeed On

Writing dataframe to CSV file is documented here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html

In every python module there is a variable __file__ which has the absolute path for the current python module. You can use it to write CSV to where that python file is located.

0
Anuj Karn On

You can join the path and pass it to to_csv method.

df.to_csv(os.path.join(cwd, "new"))