I tried to create a new file with Python26 file()/open() directly inside C:\. User does not have permission to create a new file here.
Expectation is that i receive a "Permission denied" error. However i end up receiving invalid file name/mode error on one particular host. This is breaking the error handling of my application . On all other hosts it is doing fine.
All other threads in stack over flow like Region: IOError: [Errno 22] invalid mode ('w') or filename point to wrong file names which i believe is not the case with me.
a = file("C:\\new2.txt","w") Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: [Errno 22] invalid mode ('w') or filename: 'C:\\new2.txt'
1 Answers
Whey you are calling file(path,"w")
in windows, Python calls open()
or _wopen()
with flags O_CREAT | O_TRUNC
.
Both this functions can return following codes (as described in MSDN):
EACCES
- Tried to open a read-only file for writing, file's sharing mode does not allow the specified operations, or the given path is a directory.EEXIST
- _O_CREAT and _O_EXCL flags specified, but filename already exists.EINVAL
- Invalid oflag or pmode argument.EMFILE
- No more file descriptors are available (too many files are open).ENOENT
- File or path not found.
As you can see, EACCES
is not your option as file does not exists.
Now let's take a look at flags:
_O_TRUNC
Opens a file and truncates it to zero length; the file must have write permission. Cannot be specified with_O_RDONLY
._O_TRUNC
used with_O_CREAT
opens an existing file or creates a file.
And one last thing:
if any value other than the allowed oflag values is specified, the function generates an assertion in Debug mode and invokes the invalid parameter handler, as described in Parameter Validation. If execution is allowed to continue, the function returns -1 and sets errno to
EINVAL
.
So, in your case you will not get EACESS
. Instead you will get EINVAL
(22).
You can check this question How to check if a file can be created inside given directory on MS XP/Vista? and this Python - Test directory permissions
To try to find solution. As you can see, Windows file access rights hardly can be mapped to POSIX. There are no easy solution.

- 1
- 1

- 3,009
- 17
- 27
-
If i try the same thing on another machine, i end up receiving permission denied error. I tried to check if there are permssion differences, but i see none. `>>> open("C:\\new5.txt","w") Traceback (most recent call last): File "
", line 1, in – Sudhakar May 15 '15 at 03:13IOError: [Errno 13] Permission denied: 'C:\\new5.txt'` -
@SudhakaraRao is it running the same version of Windows? I saw, that different versions of UAC + different treatment of running programs (i.e. is it running in compatibility mode) can cause funny things. – werewindle May 15 '15 at 10:26