简体   繁体   English

从我访问python调用的文件路径

[英]Accessing the filepath where I called python from

I would like to use the filepath of where I called Python from, but I have not found the solution for this yet (perhaps I'm bad at searching). 我想使用我从那里调用Python的文件路径,但是我还没有找到解决方案(也许我不擅长搜索)。

Example: 例:

Contents of foo.py : foo.py内容:

import sys
print(sys.path)
$ pwd
/Here
$ python3 folder1/foo.py
'/Here/folder1'

This is the result I currently get, but I would like to have access to '/Here'. 这是我当前得到的结果,但是我想访问'/ Here'。

Save it to a variable 将其保存到变量

import os

pypath = os.getcwd()

In general the os module will be useful for these types of things and if you want to look at all the files in the current directory(path) then its os.listdir(".") , note the "." 通常,os模块将对这些类型的事情有用,如果您要查看当前目录(路径)中的所有文件,则应使用os.listdir(".")注意"." will equal os.listdir() 等于os.listdir()

You need to use os.getcwd() from os module. 您需要使用os模块中的os.getcwd() sys.path contains list of paths in which python will search for the modules that you are importing sys.path包含python将在其中搜索要导入的模块的路径列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM