Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change the directory in python?

My script is under the directory:

'C:\\Users\\rikesh.kayastha\\project1\\daas\\src'

My script code is :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

file_name_csv = "sample.csv"

os.chdir('C:\\Users\\rikesh.kayastha\\project1\\data')
df.to_csv(file_name_csv,index=False,encoding="utf-8")

This code saves the csv file in my desired directory. But this is just for local machine. How to adjust this without mentioning the local path. The base path is just project1 I want to remove the C:\\Users\\rikesh.kayastha\\ part so that this code will work on every machine.

>Solution :

You can get the user’s home directory using pathlib with Path.home().

from pathlib import Path

file_name_csv = "sample.csv"

user_home_directory = Path.home()
project_directory = user_home_directory / "project1"

output_filepath = project_directory / file_name_csv
df.to_csv(output_filepath, index=False, encoding="utf-8")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading