在Python中访问相对路径 [英] Accessing relative path in Python

查看:121
本文介绍了在Python中访问相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行Mac OS X环境,习惯于使用〜/提供对当前用户目录的访问.

I'm running a Mac OS X environment and am used to using ~/ to provide the access to the current user's directory.

例如,在我的python脚本中,我只是尝试使用

For example, in my python script I'm just trying to use

os.chdir("/Users/aaron/Desktop/testdir/")

但想使用

os.chdir("~/Desktop/testdir/")

尝试运行此文件或目录时,没有出现此类文件或目录错误.有什么想法吗?

I'm getting a no such file or directory error when trying to run this. Any ideas?

推荐答案

您将需要使用 os.path.expanduser(path)

You'll need to use os.path.expanduser(path)

os.chdir("~/Desktop/testdir/")正在当前工作目录中寻找名为〜"的目录.

os.chdir("~/Desktop/testdir/") is looking for a directory named "~" in the current working directory.

还要注意该函数的文档-特别是,您需要正确设置$HOME环境变量以确保进行扩展.在大多数情况下,这不会有问题,但是如果不进行扩展,那可能就是原因.

Also pay attention to the documentation of that function - specifically that you'll need the $HOME environment variable set properly to ensure that the expansion takes place. Most of the time this wont be a problem but if the expansion doesn't take place, that's the likely reason.

这篇关于在Python中访问相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆