OneCompiler

How to create and open a file in Python?

I want to know how I can open a file in my system using Python. If the file doesn't exist I need to make one and open it. How can I do it?

for example, if I want to open index.txt if it exists the contents of the file should be opened else I need to make one and open,

1 Answer

5 years ago by

That's pretty easy, you can use the below code.

file = open('index.txt', 'w+')

5 years ago by Divya