30 Days of Python (21 Part Series)
If coding tutorials with math examples are the bane of your existence, keep reading. This series uses relatable examples like dogs and cats.
File handling allows you to create, read, update and delete files. I assume this is where CRUD comes from.
Using the open() function, you can create, read, and update files
#syntax open('filename', mode)
|mode||does...||if file doesn't exist...|
||read||default value, opens for reading||error if file doesn't exist|
||append||opens a file for appending||creates file if it doesn't exist|
||write||opens a file for writing||creates file if it doesn't exist|
||create||creates specified file||error if file already exists|
||text||default value, text mode|
||binary||binary mode, (e.g. images)|
This first examples let's us look at the WHOLE file
file = open('./dogs.txt','r') text = file.read(). # put a number as a parameter & get that many characters print(text) #output allllllllllllllllllllllllllllllllllllllllllllllll the words of the file print here and blah blah blah...
you may also
with open('./dogs.txt','w') as f: f.write('text about dogs')
To append = add to the end
If I want to make my file include cats, here's what I'd do
with open('./dogs.txt','a') as f: f.write('and cats')
Now the file reads: "text about dogs and cats"
import os os.remove('./dogs.txt')
If the file doesn't exist, it can't remove it and will give an error. For this case, it may be good to use an if-else condition.
import os if os.path.exist('./dogs.txt’): os.remove('./dogs.txt') else: os.remove("file doesn't exist")
Series loosely based on