python如何像r中的setwd一样更改工作路径

Python 中可以使用 os.chdir() 函数来更改工作路径。该函数的语法如下:

Python

os.chdir(path)

Use code with caution. Learn more

content_copy

其中,path 是新的路径。

例如,要将工作路径更改为 /home/user/data,可以使用以下代码:

Python

import os

os.chdir("/home/user/data")

Use code with caution. Learn more

content_copy

也可以使用 os.getcwd() 函数来获取当前工作路径。该函数的语法如下:

Python

os.getcwd()

Use code with caution. Learn more

content_copy

例如,要获取当前工作路径,可以使用以下代码:

Python

import os

print(os.getcwd())

Use code with caution. Learn more

content_copy

输出结果为:

/home/user/data

与 R 中的 setwd() 函数一样,Python 中的 os.chdir() 函数也可以使用相对路径。例如,要将工作路径更改为当前工作路径下的 data 目录,可以使用以下代码:

Python

import os

os.chdir("data")

Use code with caution. Learn more

content_copy

输出结果为:

/home/user/data/data

总而言之,Python 中更改工作路径的方法与 R 中的 setwd() 函数非常相似。

猜你喜欢

转载自blog.csdn.net/qq_52813185/article/details/135087856