如何使用 os.chdir 以“.."作为参数进入一个或多个级别 [英] How to go one or more levels using os.chdir with '..''s as arguments

查看:72
本文介绍了如何使用 os.chdir 以“.."作为参数进入一个或多个级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用.."更改 Python 中的路径以向下一层或多层作为 os.chdir() 的参数.因此,如果我在/home/usr/one 上并且我想转到 'home' 目录,那么 chdir 的 '../..' 参数就可以做到.我是否将参数包装在其他函数中?

How do I change path in Python using '..' to go down one or more levels as argument to os.chdir(). So that if I am on /home/usr/one and I want to go to 'home' directory a '../..' argument to chdir will do it. Do I wrap the argument in some other function?

推荐答案

正如你在问题中所说,如果你在目录 /home/usr/one os.chdir('../../') 将带您到 /home/.

As you say in your question, if you are in the directory /home/usr/one os.chdir('../../') will bring you to /home/.

您可以致电确认:

os.getcwd()

更改目录之前和之后.此功能将显示当前工作目录.此外,无需将 chdir() 的参数包装在另一个函数中.

Before and after changing directories. This function will show you the current working directory. Also, there is no need to wrap the argument to chdir() in another function.

请注意,当您从终端运行脚本时,脚本中的 os.chdir() 不会更改您所在的目录.换句话说,如果您在 /home/usr/one 中并使用 python myscript.py 运行脚本,则使用 os.chdir() 脚本完成时不会反映该脚本中的;您仍将位于 /home/usr/one.

Note that os.chdir() in a script will not change the directory you are in when you run the script from the terminal. In other words, if you are in /home/usr/one and run a script with python myscript.py, any directory changes made with os.chdir() within that script will not be refelected when the script finishes; you will still be in /home/usr/one.

这篇关于如何使用 os.chdir 以“.."作为参数进入一个或多个级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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