Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.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 (106k 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.6k points)
+2 votes
2 answers
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...