Casa > H > How To Create A Text File In Python

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.

  1. file = open(“testfile.txt”,”w”)  
  2. file.write(“Hello World”)  
  3. file.write(“This is our new text file”)  
  4. file.write(“and this is another line.”)  
  5. file.write(“Why? Because we can.”)  
  6. 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]

De Vitia Noe

É "eu também tenho" ou "eu também tenho"? :: Que tinha uma carreira melhor: Wayne Gretzky ou Michael Jordan?