查找当前目录和文件的目录 [英] Find current directory and file's directory

查看:157
本文介绍了查找当前目录和文件的目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,可以使用什么命令查找:


  1. 当前目录Python脚本)和

  2. 我正在执行的文件是哪里?


解决方案

要获取包含Python文件的目录的完整路径,请在该文件中写入:

  import os 
dir_path = os.path.dirname(os.path.realpath(__ file__))

(请注意,如果您已经使用 os.chdir()来更改您当前的工作目录,则上述咒语将无法正常工作,因为 __ file __ 常量是相对于当前工作目录,并且不被 os.chdir()调用更改。 / p>




要获取当前工作目录使用

  import os 
cwd = os.getcwd()






文档参考es用于上面使用的模块,常量和函数:




In Python, what commands can I use to find:

  1. the current directory (where I was in the terminal when I ran the Python script), and
  2. where the file I am executing is?

解决方案

To get the full path to the directory a Python file is contained in, write this in that file:

import os 
dir_path = os.path.dirname(os.path.realpath(__file__))

(Note that the incantation above won't work if you've already used os.chdir() to change your current working directory, since the value of the __file__ constant is relative to the current working directory and is not changed by an os.chdir() call.)


To get the current working directory use

import os
cwd = os.getcwd()


Documentation references for the modules, constants and functions used above:

这篇关于查找当前目录和文件的目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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