DEV Community

Vicki Langer
Vicki Langer

Posted on

Charming the Python: File Handling

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)
Enter fullscreen mode Exit fullscreen 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...
Enter fullscreen mode Exit fullscreen mode

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.
Python Idle and .txt file windows

with open('./dogs.txt','w') as f:
    f.write('text about dogs')
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

Now the file reads: "text about dogs and cats"

Deleting a File

import os
os.remove('./dogs.txt')
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

Series loosely based on

Top comments (6)

Collapse
 
rhymes profile image
rhymes • Edited

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!

Collapse
 
vickilanger profile image
Vicki Langer

Thanks! This looks pretty helpful. :)

Collapse
 
nycbeardo profile image
M. Stevens

This is awesome Vicki! I just started learning Python again and I plan on incorporating your series into my learning process.

Collapse
 
vickilanger profile image
Vicki Langer

Awesome! I'm happy to help and clear up anything that might not be so clear. If you have questions just ask.

Collapse
 
vickilanger profile image
Vicki Langer

😱 Thanks for letting me know. I’ll get that fixed