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
File handling allows you to create, read, update and delete files. I assume this is where CRUD comes from.
Opening a File
Using the open() function, you can create, read, and update files
#syntax
open('filename', mode)
Mode
mode | does... | if file doesn't exist... | |
---|---|---|---|
r |
read | default value, opens for reading | error if file doesn't exist |
a |
append | opens a file for appending | creates file if it doesn't exist |
w |
write | opens a file for writing | creates file if it doesn't exist |
x |
create | creates specified file | error if file already exists |
t |
text | default value, text mode | |
b |
binary | binary mode, (e.g. images) |
Reading a File
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 readlines()
and read().splitlines()
Writing to a File
If you write a file that doesn't exist, it will create one. Here's an example.
with open('./dogs.txt','w') as f:
f.write('text about dogs')
Append to a File
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"
Deleting a File
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
Top comments (5)
Hi Vicki, nice notes!
I'm going to suggest the builtin module pathlib as well, which has an object oriented interface on path navigation and manipulation. You might find it helpful!
Thanks! This looks pretty helpful. :)
This is awesome Vicki! I just started learning Python again and I plan on incorporating your series into my learning process.
Awesome! I'm happy to help and clear up anything that might not be so clear. If you have questions just ask.
😱 Thanks for letting me know. I’ll get that fixed