close

How to create a File if Not Exists in Python

Hello guys. How are you all? I hope you all fine. In this tutorial we will learn about how to create a File if Not Exists in Python. so without wasting time lets learn about of this.

How to create a File if Not Exists in Python

  1. create a File if Not Exists in Python

    To create a File if Not Exists in Python Use Open() you can create and open file in your path.So it is very useful to create a file in python. Syntax : file_obj = open("filename", "mode") Modes : w write mode r read mode w+ append mode a append mode r+ read+write mode
    a+ create a file Example: file1 = open('Myfile.txt','a+')

  2. to create a File if Not Exists in Python

    To create a File if Not Exists in Python Use touch() you can create and open file in your path.So it is very useful to create a file in python.
    myfile = Path('myfile.txt') myfile.touch(exist_ok=True) f = open(myfile)

Method 1 : Using open()

By using Open() you can create and open file in your path.So it is very useful to create a file in python.

Syntax :

file_obj  = open("filename", "mode")

Modes :

  • w write mode
  • r read mode
  • w+ append mode
  • a append mode
  • r+ read+write mode
  • a+ create a file

Example:

file1 = open('Myfile.txt','a+')

Method 2 : using touch()

By using touch() you can create and open file in your path.So it is very useful to create a file in python.

myfile = Path('myfile.txt')
myfile.touch(exist_ok=True)
f = open(myfile)

Conclusion

It’s all About this Tutorial. Hope all methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you?

Also, Read

Leave a Comment