ChatGPT解决这个技术问题 Extra ChatGPT

How to set the current working directory? [duplicate]

This question already has answers here: Equivalent of shell 'cd' command to change the working directory? (14 answers) Closed 3 years ago.

How to set the current working directory in Python?


A
Alex L

Try os.chdir

os.chdir(path) Change the current working directory to path. Availability: Unix, Windows.


Can you give me an example of format of the path? I am using os x; when I am trying to set a path I am getting an error - >>> import os >>> os.chdir(Users/Me/Desktop/M/PTS/Python/t1.py) File "", line 1 os.chdir(/Users/Me/Desktop/M/PTS/Python/t1.py) ^ SyntaxError: invalid syntax >>>
@Pooja25 The path must be a string. in addition, chdir expects a directory name, but you are specifying a file.
I usually use os.getcwd() first, and that shows me the format of the accepted input for os.chdir().
u
unutbu

Perhaps this is what you are looking for:

import os
os.chdir(default_path)

C
Community
import os
print os.getcwd()  # Prints the current working directory

To set the working directory:

os.chdir('c:\\Users\\uname\\desktop\\python')  # Provide the new path here

–1: This answer is not useful — because it was already posted six years ago.
@cpb2 Semicolons at the end of a statement are not a syntax error in Python. You can even use them to put multiple statements on one line D-: But they are certainly very bad style.
The \u in the string on the other hand is a syntax error; that should be \\u.
@jwodder - I agree with you. OTOH, there are at least 24 people for which this was useful. Perhaps it was the fact that he covered ítems in the comments of the accepted answer: 1) format of explicit paths, 2) how to get examples of such (with getcwd).... remarkable.
You need double slashes for each directory level when dealing with Windows.
P
PritamJ

It work for Mac also

import os
path="/Users/HOME/Desktop/Addl Work/TimeSeries-Done"
os.chdir(path)

To check working directory

os.getcwd()

Python one of the core ideas of python is to work cross-plattform.
Thanks for this example, I was trying (the usual) "~/etc" without success.
@PatrickT if you want to expand ~, you need to use os.path.expanduser("~/etc"), which will then expand to the full path (/path/to/homedir/etc)
V
Vikrant

people using pandas package

import os
import pandas as pd

tar = os.chdir('<dir path only>') # do not mention file name here
print os.getcwd()# to print the path name in CLI

the following syntax to be used to import the file in python CLI

dataset(*just a variable) = pd.read_csv('new.csv')

Why is the os.chdir command different for panda usage?
If you need to read file, you don't need to change working directory. You can use absolute or relative path. You can use os.path.dirname(__file__) if you need to be relative to executed file for example