How to create a text file using Python

Syntax:

with open("test.txt", "w") as file:
    file.write("Content of the file")

Python creates a text file with the open method and the "w" parameter.

Example:

This example defines a variable containing the file name. The file is opened using the variabled and the "w" as write parameter. This way the file will be created. The content is written in the file using the write method. The file object is closed automatically.


inputFile = "test.txt"

with open(inputFile, "w") as file:
    file.write("Content of the file")
    print( inputFile + " Created" )
    

The output will be:

$ python createTextFile.py
test.txt Created

$ cat test.txt
Content of the file
$

The "w" parameter creates the file, if the file already exists its content is overwritten. Passing the parameter "a" appends the content in the file and doesn't recreate the file.


References:

Python

Share this article:

Recent Comments