excalibur
excalibur

Reputation: 944

Python open(path, 'w') fails to create file

I am seeing bizarre behavior with Python open(.., 'w') on Linux. I create a bunch of files (file1...file100) in a new dir, each with:

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

If the dir is empty, it always fails with:

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

There is no issue with permissions whatsoever.

If I manually create "touch mydir/file1", then run the Python script again, the rest of the files get created no problem.

I am using Python 2.7.

Anyone seen this?

Upvotes: 4

Views: 4020

Answers (1)

zhangxaochen
zhangxaochen

Reputation: 34017

I'm reproducing the error:

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'

the name in open(name, ...) should be file name or absolute path, no relative path allowed. If path ../mydir exists, try this:

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

or use the absolute path of the file to open:

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

Upvotes: 4

Related Questions