0 votes
1 view
in Python by (43.2k points)

What is the best way to open a file as reading/write if it exists, or if it does not, then create it and open it as read/write? From what I read, file = open('myfile.dat', 'rw') should do this, right?

It is not working for me (Python 2.6.2) and I'm wondering if it is a version problem, or not supposed to work like that or what.

The bottom line is, I just need a solution to the problem. I am curious about the other stuff, but all I need is a nice way to do the opening part.

1 Answer

0 votes
by (107k points)

When we use the following approach it has an advantage which is, the file is properly closed at the block's end, even if an exception is raised on the way. It's equivalent to try-finally but much shorter.

with open("file.dat","a+") as f: 

f.write(...) 

...

When we use a+ it opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

Related questions

0 votes
1 answer
asked Sep 25, 2019 in Python by Sammy (47.8k points)
+3 votes
2 answers
0 votes
1 answer
0 votes
1 answer
asked Jul 3, 2019 in Python by Sammy (47.8k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...