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
- Opening a file
To open a file, you use
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") print(file.read())
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!") file.close()
Always, always use
file.close() or it wont write.
To overwrite a file use:
file = open("file.txt", "w") file.write("contents") file.close()
So if file.txt had
Hello there! in it, it would now have
contents in it.
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.
It's much, much better to use
with, because even if there is an exception or something else, the file is closed:
with open("main.py") as f: print(f.read())
This is a Quine, and, by the way, there are also modes for binary: rb, wb, ab, and wb+