1

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.

Patrik
  • 499
  • 1
  • 7
  • 24
J.Doe
  • 109
  • 1
  • 1
  • 8

3 Answers3

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

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

Stefan
  • 897
  • 4
  • 13
  • I need to run the script in different folders in a way such that once it is executed the output file is written in the current working directory, so that I do not have to insert and modify manually the path in code everytime! I was not able to apply your method in the case where part of the path is a string cwd = os.getcwd(). – J.Doe Dec 02 '20 at 10:52
  • Please look at my edit. That way the file will always be stored in the current directory. – Stefan Dec 02 '20 at 10:57
0

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

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

df.to_csv(os.path.join(cwd, "new"))
Gigioz
  • 367
  • 5
  • 19
Anuj Karn
  • 42
  • 5