我想在python中构建一个绝对路径,同时对路径分隔符之类的东西保持相当的清醒。edit0:例如在我的文件系统/etc/init.d(或C:\etc\init.d在w32上),我只想从元素etc和init.d构造它(在w32上,我可能还需要一个磁盘ID,像C:)为了不必担心路径分隔符,os.join.path()显然是首选工具。但似乎这只会创建relative路径:print("MYPATH:%s"%(os.path.join('etc','init.d'),)MYPATH:etc/init.d添加一个虚拟的第一个元素(例如'')没有任何帮助:print("MYPATH:%s"%(os
在Jupyter中我自己的小模块没有加载,但在python/bpython中一切都很好。打字时importsysprint(sys.path)我的模块的路径不会在Jupyter中显示,但在python/bpython中它仍然存在。我正在使用:.bashrc中的PYTHONPATH以包含我的模块,虚拟环境中的Jupyter和bpython。最相似的问题是这个Cannotimportmodulesinjupyternotebook;wrongsys.path如何配置Jupyter以自动加载我的模块? 最佳答案 这是我在jupyterno
我倾向于只对路径('/')使用正斜杠,python也很喜欢它在Windows上。在os.path.join的描述中,如果你想跨平台,这是正确的方法。但是当我使用它时,我得到了混合斜线:importosa='c:/'b='myFirstDirectory/'c='mySecondDirectory'd='myThirdDirectory'e='myExecutable.exe'printos.path.join(a,b,c,d,e)#Result:c:/myFirstDirectory/mySecondDirectory\myThirdDirectory\myExecutable.exe
他们是一样的,但是我应该使用哪一个?http://docs.python.org/library/os.html:os.sepThecharacterusedbytheoperatingsystemtoseparatepathnamecomponents.Thisis'/'forPOSIXand'\'forWindows.Notethatknowingthisisnotsufficienttobeabletoparseorconcatenatepathnames—useos.path.split()andos.path.join()—butitisoccasionallyuseful.
问题PEP8有一条关于将导入放在文件顶部的规则:Importsarealwaysputatthetopofthefile,justafteranymodulecommentsanddocstrings,andbeforemoduleglobalsandconstants.但是,在某些情况下,我可能想做一些类似的事情:importsyssys.path.insert("..",0)importmy_module在这种情况下,pep8命令行实用程序会标记我的代码:E402modulelevelimportnotattopoffile通过sys.path修改实现PEP8合规性的最佳方法是什么
在今天之前,我从未注意到在我的一些包上定义的__path__属性。根据文档:Packagessupportonemorespecialattribute,__path__.Thisisinitializedtobealistcontainingthenameofthedirectoryholdingthepackage’s__init__.pybeforethecodeinthatfileisexecuted.Thisvariablecanbemodified;doingsoaffectsfuturesearchesformodulesandsubpackagescontainedin
我正在检查目录是否存在,但我注意到我使用的是os.path.exists而不是os.path.isdir。两者都工作得很好,但我很好奇使用isdir而不是exists有什么优势。 最佳答案 os.path.exists如果有一个具有该名称的常规文件,也将返回True。os.path.isdir仅当该路径存在并且是目录或指向目录的符号链接(symboliclink)时才会返回True。 关于python-os.path.exists与os.path.isdir之间的优缺点,我们在Stack
我有一个名为example_file.py的文件,我想从其他各种文件中使用它,所以我决定将example_file.py添加到sys.路径并将此文件导入另一个文件以使用该文件。为此,我在IPython中运行了以下命令。importsyssys.pathsys.path.append('/path/to/the/example_file.py')print(sys.path)我可以看到我刚刚添加的路径,当我尝试从另一个目录路径导入这个文件时:importexample_file它工作得很好,但是一旦我从IPython出来,再次进入它,检查sys.path,我发现我添加的路径不存在,那怎么
在多个开源项目中,我见过有人用os.path.abspath(os.path.realpath(__file__))来获取当前文件的绝对路径。但是,我发现os.path.abspath(__file__)和os.path.realpath(__file__)产生相同的结果。os.path.abspath(os.path.realpath(__file__))好像有点多余。人们使用它有什么原因吗? 最佳答案 对于您所述的场景,没有理由将realpath和abspath结合起来,因为os.path.realpath在返回结果之前实际上调
另一位开发人员和我不同意应该使用PYTHONPATH还是sys.path来允许Python在用户(例如开发)目录中查找Python包。我们有一个具有典型目录结构的Python项目:Projectsetup.pypackage__init__.pylib.pyscript.py在script.py中,我们需要importpackage.lib。当软件包安装在site-packages中时,script.py可以找到package.lib。但是,当从用户目录工作时,需要做其他事情。我的解决方案是将我的PYTHONPATH设置为包含"~/Project"。另一个开发者想把这行代码放在scri