2014-01-08 61 views
1

我想运行一个python模块,搜索一个表,并从该表中的一些celss(使用变量“LayerExpression”)提取数据。在某些情况下,该单元格包含另一个python文件的路径名称(例如,表格单元格可能包含以下路径名称:'C:\ Users \ me \ Documents \ Working \ PyFiles \ Example.py')。我的python程序将每个单元格值赋给变量“CommentsExpression”,然后检查变量以查看它是否确实引用了一个到现有文件的路径名(使用os.path.exists())。如果是这样的话,那么我的程序会将其他python文件作为模块导入,并从中提取特定变量 - 在本例中为变量“expression”。Python os.path.exists问题与变量

我的问题是,当我从表中提取路径名时,将其分配给变量“CommentsExpression”,并通过os.path.exists()运行它,它会一直变为false - 即使文件路径确实存在。我曾尝试使用r'[路径名]',但没有运气作为变量。我的代码示例如下。

import arcpy, os, re, array, sys, glob 
from arcpy import env 

CommentsExpression = '' 
LayerExpression = '"Database - Fish Species"' 
rows = arcpy.SearchCursor(r'C:\Users\me\Documents\Working\PyFiles\Master_Table.py') 
for row in rows: 
LayerField = row.getValue("Layer") 
if LayerField == LayerExpression: 
    CommentsExpression = CommentsExpression = row.getValue(str("Comments")) 
    print os.path.exists(CommentsExpression) 
    CommentsExpressionOutput = os.path.basename(CommentsExpression) 
    CommentsExpressionOutput = CommentsExpressionOutput.split('.') 
    CommentsExpressionOutput = str(CommentsExpressionOutput[0]) 
    if os.path.exists(CommentsExpression) == True: 
     print 'True' 
     pyFile = __import__(CommentsExpressionOutput) 
     print pyFile.codeblock 
    else: 
     print 'False' 
+1

CommentsExpression是否采用绝对路径? – praveen

+0

他们是完整的路径名称,是的。 –

+0

所以你的评论让我思考,并且我改变了以下一行'if os.path.exists(CommentsExpression)== True:' to if'os.path.exists(os.path.abspath(CommentsExpression))= =真',到目前为止,它似乎正在工作! –

回答

0

感谢praveen帮助我。如果我从

if os.path.exists(CommentsExpression) == True:' 

改变以下行来代替

if os.path.exists(os.path.abspath(CommentsExpression)) == True 

它似乎工作。

+0

我希望你不是要把整个表达式放在单引号内。 – cpburnz

+0

不,我没有。你是对的。我只是注意到了我自己。 –