Alex Rivera | Logout

does write mode create a new file if not existing?

Asked 2010-06-22T16:15:38.877
24

I'm trying to write to a file that does not already exist using 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?

Edit
Report

1 Answer

4

[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.

answered 2010-06-22T16:19:35.090

Your Answer