pythondataframecsvgetcwd

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


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.


Solution

  • cwd = os.getcwd()
    path = cwd + "/new"
    df.to_csv(path)
    

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