tags:

views:

77

answers:

4

does write mode in file create a file if not existing??

a=open ('C:/c.txt' , 'w')

create a file x.txt if not existed.. how to create a file for writing if it does not as it is giving me error message saying there is no such file. when used the above line of code

A: 

If you're asking how to be warned when the file doesn't exist, then you need to explicitly check for that.

See here

Daenyth
+1  A: 

Yes, 'w' is specified as creating a new file -- as the docs put it,

'w' for writing (truncating the file if it already exists),

(clearly inferring it's allowed to not already exist). Please show the exact traceback, not just your own summary of it, as details matters -- e.g. if the actual path you're using is different, what's missing might be the drive, or some intermediate directory; or there might be permission problems.

Alex Martelli
+1  A: 

[Edited to reflect that the problem is likely not forward vs. back slash]

If I understood correctly, you want the file to be automatically created for you, right?

open in write mode does create the file for you. It would be more clear if you told us the exact error you're getting. It might be something like you not having permission to write in C:.

I had previously suggested that it might be because of the forward slash, and indicated that the OP could try:

a = open(r'C:\c.txt', 'w')

Note the r before the file path, indicating raw mode (that is, the backslash won't be interpreted as special).

However, as Brian Neal pointed out (as well as others, commenting elsewhere), that's likely not the reason for the error. I'm keeping it here simply for historical purposes.

rbp
It's not the forward slash. His code snippet works fine for me on Windows.
Brian Neal
This occurred to me a bit later. I'm still waiting for the OP to give us the error, but I'll edit my answer in the meantime. Thanks :)
rbp
+1  A: 

You most probably are trying to write to a directory that doesn't exist or one that you don't have permission writing to.

If you want to write to C:\foo\bar\foobar.txt then make sure that you've got a C:\foo\bar\ that exists (and in case permissions work on Windows, make sure you've got the permission to write there).

Now when you open the file in write mode, a file should be created.

Umang
I bet this is a permissions problem. The default for Vista and Windows 7 is not to allow ordinary users to write files in the root directory.
Charles E. Grant