以'w'模式出现文件不存在错误
我遇到了一个奇怪的情况,跟Python内置的file()
函数有关。我在用unittest-xml-reporting这个Python包来生成我的单元测试结果。下面是我用来打开一个文件以便写入的代码,这个文件显然是不存在的:
report_file = file('%s%sTEST-%s.xml' % \
(test_runner.output, os.sep, suite), 'w')
(这段代码来自这个包的Github页面)
但是,我却收到了以下错误信息:
...
File "/home/[...]/django-cms/.tox/pytest/local/lib/python2.7/site-packages/xmlrunner/__init__.py", line 240, in generate_reports
(test_runner.output, os.sep, suite), 'w')
IOError: [Errno 2] No such file or directory: './TEST-cms.tests.page.NoAdminPageTests.xml'
我觉得这很奇怪,因为根据Python的文档,如果使用w
模式,文件应该在不存在时被创建。为什么会出现这种情况,我该怎么解决呢?
3 个回答
2
file
这个命令可以用来创建一个文件,但它不能用来创建一个文件夹。你需要先创建文件夹,具体的步骤可以参考 这里。
2
来自 man 2 read
ENOENT O_CREAT is not set and the named file does not exist. Or, a
directory component in pathname does not exist or is a dangling
symbolic link.
随你选择 :)
用人类能理解的话说:
- 当这个命令运行时,你当前的工作目录
./
已经被移除了, ./TEST-cms.tests.page.NoAdminPageTests.xml
存在,但它是一个指向无处的符号链接,- 你在打开文件时使用的 "w" 可能出现了问题,比如你重新定义了
file
这个内置函数。
0
看起来需要创建的文件是在一个已经被删除的文件夹里尝试创建的(因为路径是.
,很可能测试文件夹在那时已经被删除了)。
我通过给test_runner.output
提供一个绝对路径来解决这个问题,现在结果文件成功创建了。