Python open(path,'w')无法创建文件

时间:2014-02-21 17:06:27

标签: python python-2.7

我在Linux上看到Python打开(...,'w')的奇怪行为。 我在一个新目录中创建了一堆文件(file1 ... file100),每个文件都包含:

 with open(nextfile, 'w') as f:

如果目录为空,则总是失败:

IOError: [Errno 2] No such file or directory: '../mydir/file1'

任何权限都没有问题。

如果我手动创建“touch mydir / file1”,则再次运行Python脚本, 创建其余文件没问题。

我正在使用Python 2.7。

有人见过这个吗?

1 个答案:

答案 0 :(得分:4)

我正在复制错误:

In [482]: nextfile='../mydir/file1'

In [483]: with open(nextfile, 'w') as f:
     ...:     pass
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-483-fa56c00ac002> in <module>()
----> 1 with open(nextfile, 'w') as f:
      2     pass

IOError: [Errno 2] No such file or directory: '../mydir/file1'

name中的open(name, ...)应该是文件名或绝对路径,不允许相对路径。如果路径../mydir存在,请尝试以下操作:

In [484]: import os
     ...: os.chdir('../mydir')
     ...: nextfile='file1'
     ...: with open(nextfile, 'w') as f:
     ...:     #do your stuff
     ...:     pass

或使用文件的绝对路径打开:

nextfile=os.path.join(os.getcwd(), '../mydir/file1')