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.
Hello! Welcome to my pog tutorial :>
So...
This tutorial is gonna show you how to open files in python!
It will include...
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:
which is the same as
To get the value in the file, use:
So if I wanted to print the contents of a file I would do:
The output should be the file contents.
Adding to a file (appending)
To append to a file use:
The "a" stands for append, and adds ti the file.
So, to add to a file do:
Remember:
Always, always use
file.close()
or it wont write.Overwriting files.
To overwrite a file use:
So if file.txt had
Hello there!
in it, it would now havecontents
in it.Creating files.
To create a file use:
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.
Good intro. Could you create an example repl?
Um idk lol @malvoliothegood