ChatGPT解决这个技术问题 Extra ChatGPT

如何设置当前工作目录? [复制]

这个问题在这里已经有了答案: Equivalent of shell 'cd' command to change the working directory? (14 个回答) 3 年前关闭。

如何在 Python 中设置当前工作目录?


A
Alex L

试试os.chdir

os.chdir(path) 将当前工作目录更改为路径。可用性:Unix、Windows。


你能给我一个路径格式的例子吗?我正在使用 os x;当我尝试设置路径时出现错误 - >>> 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: 无效语法 >>>
@Pooja25 路径必须是字符串。此外,chdir 需要一个目录名,但您指定的是一个文件。
我通常首先使用 os.getcwd(),它显示了 os.chdir() 接受的输入格式。
u
unutbu

也许这就是您正在寻找的:

import os
os.chdir(default_path)

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

设置工作目录:

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

–1:这个答案没有用——因为它已经在六年前发布了。
@cpb2 语句末尾的分号不是 Python 中的语法错误。你甚至可以用它们将多个语句放在一行 D-:但它们肯定是非常糟糕的风格。
另一方面,字符串中的 \u is 是语法错误;那应该是\\u
@jwodder - 我同意你的看法。 OTOH,至少有 24 个人对此有用。也许是因为他在已接受答案的评论中涵盖了以下项目:1)显式路径的格式,2)如何获得此类示例(使用 getcwd).... 了不起。
处理 Windows 时,每个目录级别都需要双斜杠。
P
PritamJ

它也适用于 Mac

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

检查工作目录

os.getcwd()

Python python 的核心思想之一是跨平台工作。
感谢这个例子,我尝试(通常的)"~/etc"但没有成功。
@PatrickT 如果要扩展 ~,则需要使用 os.path.expanduser("~/etc"),然后它将扩展为完整路径 (/path/to/homedir/etc)
V
Vikrant

使用 pandas 包的人

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

以下语法用于在 python CLI 中导入文件

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

为什么 os.chdir 命令对 panda 的使用有所不同?
如果您需要读取文件,则无需更改工作目录。您可以使用绝对或相对路径。例如,如果您需要相对于已执行的文件,您可以使用 os.path.dirname(__file__)