Tags
python
Asked 3 years ago
16 Aug 2021
Views 479
Patricia

Patricia posted

How do you create a file if it does not exist in Python?

How do you create a file if it does not exist in Python?
Mitul Dabhi

Mitul Dabhi
answered Aug 16 '21 00:00

open() function can be used to open a file and also create a file if does not exists in Python.
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
open() method have first argument is file path which we want to create
open() method have second argument is mode we need to pass here 'w'
we keep other argument empty or dont pass anything for other parameter

so
open('filepath','w') is used to create a file if file does not exits


Test code :

open("test1.py","w")


if you don't pass mode of file open :
open("test1.py")
then it will generate the error if the file doesn't exist :
No such file or directory:
so it is compulsory to pass the "w" at the second argument.
duglus

duglus
answered Aug 16 '21 00:00

Following is step by step process to create a file if it does not exist in Python :

1. decide which file need to check and create if not exits :
path ='array.txt'

2. first check file is exits or not in Python
2a . import Path from pathlib in Python
Path object is used late for File realted manuplication

p = Path(path)

here Path(file_path), here argument file_path is the absolute or relative path of the file which we want to check
Path() returns the Path object which is used later with is_file() and touch()

2b. check file exits or not by is_file() in Python

if p.is_file()==False :
	print('File does not exits')

is_file() can be used to see the file is exists or not . if not it will return False which we checked in above condition with if

3. create the new file if file does not exits in Python

if p.is_file()==False :
	p.touch()


touch() function is used to create file with given path at Path object.


Following code is used to create file if file dont exits :

from pathlib import Path
path ='array.txt'
p = Path(path)
if p.is_file()==False :
	p.touch()

Post Answer