是否可以指定以前的目录python? [英] Is it possible to specify the previous directory python?

查看:233
本文介绍了是否可以指定以前的目录python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我已经做了一些研究,没有一直在进行研究能够找到我正在寻找的答案。基本上,我想确定Python中是否有一个函数可以在shell中执行类似于 cd - 的操作。



我一般不希望输入完整的路径名,并且具有相对于指定环境的所有路径。



示例:
我有我的脚本所在的主目录 python-scripts ,我有每个测试环境的文件夹演示,以及每个测试环境的截图文件夹演示截图



如果我想使用Python保存屏幕截图,而在演示目录中工作时,我只需将其发送到以下目录: demo-截图,使用路径'/ demo-screenshots / example.png'。问题是我不明白如何移回目录。



谢谢。

解决方案

您正在寻找更改工作目录? python中的操作系统模块有很多功能可以帮助您。 p>

  import os 
os.chdir(path)

路径正在..上传一个目录。如果您需要检查目录更改之前/之后的位置,您可以发出 getcwd()命令:

  mycwd = os.getcwd()
os.chdir(..)
#do在父目录中的东西
os.chdir(mycwd )#返回你来自


I am attempting to make a Python testing script module self-contained directory-wise for scalability and maintainability purposes.

I have done some research and haven't been able to find the answer i'm looking for. Basically, I would like to determine if there is a function in Python that can do something similar to cd - in shell.

I would generally like to avoid typing in full path-names, and have all the paths relative to a specified environment.

Example: I have my main directory where my scripts are located python-scripts, I have folders for each testing environment demo, and a screenshot folder for each testing environment demo-screenshots.

If i wanted to save a screenshot to the screenshot with Python, while working in the demo directory, I would just send it to the directory below: demo-screenshots, using the path '/demo-screenshots/example.png'. The problem is that I don't understand how to move back a directory.

Thank you.

解决方案

You're looking to change the working directory? The OS module in python has a lot of functions to help with this.

import os
os.chdir( path )

path being ".." to go up one directory. If you need to check where you are before/after a change of directory you can issue the getcwd() command:

mycwd = os.getcwd()
os.chdir("..")
#do stuff in parent directory
os.chdir(mycwd)     # go back where you came from

这篇关于是否可以指定以前的目录python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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