How to create a text file using Python


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.


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
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.



Recent Comments