Python os.isfile断言失败

时间:2012-09-14 06:46:49

标签: python

所以我在打开文件进行阅读时遇到问题,所以我决定尝试一下os.isfile断言:

from Android_API_Parser import Android_API_Parser
import os.path

assert os.path.isfile("D:\Work\Python Workspace\Android_API_Parser\test.txt")

tester = Android_API_Parser()
tester.setFile("test.txt")
tester.parse()

断言失败了:

Traceback (most recent call last):
    File "D:\Work\Python Workspace\Android_API_Parser\src\Android_API_Tester.py", line         
    9, in <module>
assert os.path.isfile("D:\Work\Python Workspace\Android_API_Parser\test.txt")
AssertionError

我已经打开了我试图打开的文件的路径并将其粘贴到下面:

D:\Work\Python Workspace\Android_API_Parser\test.txt

为什么它甚至失败了断言的任何想法?除非我真的很累,否则文件显然位于那里。我甚至尝试使用“/”和“\”,即使包含转义字符。

1 个答案:

答案 0 :(得分:3)

string literal中,您必须使用另一个反斜杠转义反斜杠,使用原始字符串或使用正斜杠。否则,"\t"将成为仅包含制表符的字符串。

尝试以下任何一项:

assert os.path.isfile("D:\\Work\\Python Workspace\\Android_API_Parser\\test.txt")
assert os.path.isfile(r"D:\Work\Python Workspace\Android_API_Parser\test.txt")
assert os.path.isfile("D:/Work/Python Workspace/Android_API_Parser/test.txt")
assert os.path.isfile(os.path.join("D:", "Work", "Python Workspace",
                                   "Android_API_Parser", "test.txt"))

该文件也可能不是常规文件。使用os.path.exists查看是否存在。

您可能也没有足够的权限来查看文件或您期望的文件名may be localized。要调试它,请运行:

path = ["Work", "Python Workspace", "Android_API_Parser", "test.txt"]
f = 'D:'
for p in path:
  f = os.path.join(f, p)
  print(f)
  assert os.path.exists(f)
assert os.path.isfile(f)
相关问题