【问题标题】:Python os.path.exists issue with variablesPython os.path.exists 变量问题
【发布时间】:2014-01-08 21:35:57
【问题描述】:

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

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

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'

【问题讨论】:

  • CommentsExpression走的路径是绝对路径吗?
  • 它们是完整的路径名,是的。
  • 所以你的评论让我思考,我将以下行从 'if os.path.exists(CommentsExpression) == True:' 更改为 if 'os.path.exists(os.path. abspath(CommentsExpression)) == True' 到目前为止它似乎正在工作!

标签: python arcgis arcpy


【解决方案1】:

感谢 praveen 帮助我解决这个问题。如果我从

更改以下行
if os.path.exists(CommentsExpression) == True:'

改为

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

它似乎有效。

【讨论】:

  • 我希望你不是想把整个表达式放在单引号内。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-23
  • 2011-11-21
  • 2013-09-04
  • 2014-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多