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, 2019 in Python by David
2,731 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, 2019 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
177 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, 2019 in Python by Omkar
• 69,030 points
166 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, 2019 in Python by Nymeria
• 3,520 points
5,117 views
0 votes
2 answers

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

a = int (input('enter number')) num = a sum ...READ MORE

answered Jul 16 in Python by amrut
• 240 points
114 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, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,466 views
0 votes
0 answers
+4 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,800 points
1,095 views
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,780 points
208 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, 2019 in Python by Nymeria
• 3,520 points
366 views