Epic python tutorial: Manipulating files
angrydoge (318)

Hello! Welcome to my pog tutorial :>


This tutorial is gonna show you how to open files in python!

It will include...

  • How top open a file
  • Printing text from a file into the console
  • Adding text to a file
  • Overwriting a file
  1. Opening a file
    To open a file, you use
open("filename.txt", "letter")

The letters are:
"r" - Read - Opens a file to read. Creates an error if specified file doesnt exist.

"a" - Append - Opens a file to add content to. If it doesnt exist, it creates the file.

"w" - Write - Opens a file for writing. It creates a file if it doesnt exist.

"x" - Create - Creates a file. Returns error if it exists.

Opening a file for reading.

To open a file to read, you can do this:

file = open("file.txt")

which is the same as

file = open("file.txt", "r")

To get the value in the file, use:


So if I wanted to print the contents of a file I would do:

file = open("file.txt", "r")

The output should be the file contents.

Adding to a file (appending)

To append to a file use:

file = open("file.txt", "a")

The "a" stands for append, and adds ti the file.
So, to add to a file do:

file = open("file.txt", "a")
file.write("This is some content!")


Always, always use file.close() or it wont write.

Overwriting files.

To overwrite a file use:

file = open("file.txt", "w")

So if file.txt had Hello there! in it, it would now have contents in it.

Creating files.

To create a file use:

file = open("file.txt", "x")

If you use file.write() it will probably return errors.
If "file.txt" already exists, it will return an error also. So make sure the file does not already exist.

Okay, thats it for my tutorial! I hope it was good! bai!

this actually took a long time for a short tutorial, its hard. pls no judge me.
You are viewing a single comment. View All
malvoliothegood (781)

Good intro. Could you create an example repl?