Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting "IOError: [Errno 2] No such file or directory: 'myoutfile.csv' " error in Python

Tags:

python

file-io

I am using this line to create a new file (the file does not exist):

with open(outfilename, 'rwb') as outfile:

And it gets this error:

IOError: [Errno 2] No such file or directory: 'myoutfile.csv'

I am trying to create this file, and I thought if I used 'w' that would create it if it doesn't exist. If it is permissions, how do I create a new folder and refer to its path?

like image 992
Dan Avatar asked May 22 '26 23:05

Dan


2 Answers

The open mode passed to the open() function accepts only a specific few combinations of letters. In your case, 'rwb' is not one of those combinations, and Python is perhaps assuming that you meant 'rb'. Try:

with open(outfilename, 'wb') as outfile:

This opens the file for writing. If you need to both write to and read from the same handle, use:

with open(outfilename, "w+b") as outfile:
like image 182
Greg Hewgill Avatar answered May 24 '26 12:05

Greg Hewgill


I'm pretty certain rwb isn't a valid mode for open. Depending on the behaviour desired, you may have to opt for one of r+b or w+b.

Use rb is you want to read an existing file.

Use r+b is you want to read/write an existing file.

Use wb is you want to write an existing or non-existing file (will truncate an existing file first).

Use w+b is you want to read/write an existing or non-existing file (will truncate an existing file first).

Use a combination if you don't want truncation of an existing file, something like (pseudo-code, obviously):

open with "r+b"
on error:
    open with "w+b"
like image 31
paxdiablo Avatar answered May 24 '26 12:05

paxdiablo