How to create a text file in Python
Create a text file
Using a simple text editor, let’s create a file. You can name it anything you like, and it’s better to use something you’ll identify with.
For the purpose of this tutorial, however, we are going to call it “testfile.txt”.
Just create the file and leave it blank.
To manipulate the file, write the following in your Python environment.
- file = open(“testfile.txt”,”w”)
- file.write(“Hello World”)
- file.write(“This is our new text file”)
- file.write(“and this is another line.”)
- file.write(“Why? Because we can.”)
- file.close()
Naturally, if you open the text file – or look at it – using Python you will see only the text we told the interpreter to add.
[math]$ cat testfile.txt [/math]
[math]Hello World [/math]
[math]This is our new text file [/math]
[math]and this is another line. [/math]
[math]Why? Because we can.[/math]