2012-03-27 76 views
4

我有以下代码:蟒蛇os.path.realpath不能正常工作

os.chdir(os.path.dirname(os.path.realpath(__file__)) + "/../test") 
path.append(os.getcwd()) 
os.chdir(os.path.dirname(os.path.realpath(__file__))) 

哪些应该增加/../test到Python路径,它这样做,它全部采用PyDev的平稳运行之后的月食。

但是,当从控制台第二os.chdir我午餐相同的应用程序做错了事,实际上是错误的事情是os.path.realpath(__file__) CUS它的../originalFolder/myFile.py代替返回../test/myFile.py。当然,我可以通过使用固定的os.chdir("../originalFolder")来解决这个问题,但这对我来说似乎有点不对劲,但这对于日食和控制台都有效。

P.S.我使用os.getcwd()实际上是因为我想确保没有这样的文件夹已经添加,否则我不必切换目录的

那么,我的方法有什么问题,或者我已经搞砸了吗? ?或者是什么? :)

在此先感谢! :)

回答

6

看看什么是价值__file__。它不包含脚本的绝对路径,它是来自命令行的值,所以它可能类似于“./myFile.py”或“myFile.py”。此外,realpath()不会使路径成为绝对路径,因此在不同目录中调用的realpath(“myFile.py”)仍将返回“myFile.py”。

我认为你应该做ssomething这样的:

import os.path 

script_dir = os.path.dirname(os.path.abspath(__file__)) 
target_dir = os.path.join(script_dir, '..', 'test') 
print(os.getcwd()) 
os.chdir(target_dir) 
print(os.getcwd()) 
os.chdir(script_dir) 
print(os.getcwd()) 

在我的电脑(Windows)中我已经导致这样的:

e:\parser>c:\Python27\python.exe .\rp.py 
e:\parser 
e:\test 
e:\parser 

e:\parser>c:\Python27\python.exe ..\parser\rp.py 
e:\parser 
e:\test 
e:\parser 

注:如果您关心的兼容性(你不喜欢奇怪的路径错误),每当你合并路径时,你应该使用os.path.join()

注:我知道我的解决方案非常简单(记住绝对路径),但有时候最简单的解决方案是最好的。

+3

'realpath()'使路径绝对 – 2013-02-18 07:20:24

+0

[Here](http://helpful.knobs-dials.com/index.php/Python_usage_notes/Filesystem_stuff)是哪个命令做了什么的一个很好的总结。 – 2013-02-18 07:27:05

+0

虽然这不是这个topi最流行的问题,但这个答案是最正确的。谢谢 ! – egelev 2015-06-25 11:40:47