How to Create a File in Python 


               


How to Create a File in Python



Python


In this article, we show how to create a file in Python.

Basically, what is meant is Python can create a file from scratch using the open() function.

Say, if we use the open() function and, inside of it, specify a file that doesn't currently exist in the directory, Python will create the file.

So, say if we have the statement, openfile= open('file.txt', 'a') and the file, file.txt, doesn't exist in the current working directory, then Python will create that file.

So, in the code below, Python will create the file, file.txt.



So, first, we must import the os module.

After this, we create the chores.txt file with the open() function. We put it in 'a' mode for append. Once this line is executed, then the chores.txt file is created.

After this, we then write to the chores.txt file. We do this through the write() function. We take the choresfile variable and use the write() function on it to write to the file. Today, I did all those chores, so those are what came to my head.

After this, we close the file, or else the contents will not have been written to it.

And this is all that is required to create a file in Python.

In this example, we create a text file (.txt). However, this can really be any type of file, such as an HTML file, a PHP file, etc.


Related Resources



HTML Comment Box is loading comments...