Open a file if it exists or create and open it does not exists - Python

0 votes
I would like to open a file in write mode and if the file does not exist, I would like the file to be created. How do I do that?
Jun 20 in Python by David
20 views

1 answer to this question.

0 votes

You can use this:

f = open("ex.txt","w+")

Here the first argument ex.txt is the filename and w means the file has to open in the write mode and + will make sure a new file called ex.txt is created if it does not exist.

answered Jun 20 by Jason

Related Questions In Python

0 votes
1 answer

Create and open a file in Python

file = open('text.txt', 'w+) READ MORE

answered May 24, 2018 in Python by Nietzsche's daemon
• 4,260 points
52 views
0 votes
1 answer

How to print a message or the error if a file is not found?

To print the message that file is not ...READ MORE

answered Jan 2 in Python by Omkar
• 67,380 points
28 views
0 votes
1 answer

How do I check if input string is a valid regular expression or not in Python?

Hi. Good question! Well, just like what ...READ MORE

answered Feb 12 in Python by Nymeria
• 3,520 points
70 views
0 votes
1 answer

What is the python logic to check if a number is armstrong number or not?

number = int(input("enter a number")) s = 0 temp ...READ MORE

answered Jul 30 in Python by Mohammad
• 3,060 points
21 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 215 views
+4 votes
6 answers
0 votes
1 answer

Is there a foreach function in python and is there a way to implement it if there isnt any

Every occurence of "foreach" I've seen (PHP, ...READ MORE

answered Aug 31, 2018 in Python by charlie_brown
• 7,720 points
79 views
0 votes
1 answer

How to create and read from a temporary file in Python?

Hi, there is a very simple solution ...READ MORE

answered Jan 29 in Python by Nymeria
• 3,520 points
55 views