does write mode create a new file if not existing?
I'm trying to write to a file that does not already exist usi开发者_Python百科ng a file context manager.
a=open ('C:/c.txt' , 'w')
The above does not succeed. How would I create a file for writing if it does already exist?
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.
[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.
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.
If you're asking how to be warned when the file doesn't exist, then you need to explicitly check for that.
See here
精彩评论