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()