Manipulating files

Hey there! Welcome back to the Python basics tutorial. Today we'll start to do some fun stuff, like manipulating files.

Let's say you have a text file with data. You want to read the text file and print it to the console. For that, we'll have to use the open function.

Setting up the files

First of all, create a new directory/folder and create a Python file inside it called test.py or anything else you would like to to be, just make sure it ends with .py. Now, make another file called test.txt and put the following text inside it:

Hell is empty and all the devils are here.

Now, open the Python file and type this:

f = open('test.txt', 'r')

Done. We've opened a file. We're passing two arguments to open : The path to the file we're opening, and the mode we want to open it in. A quick list of the modes:

r - Read mode ( To read plaintext files) w - Write mode (To write to files) a - Append mode (To add more text to the end of a file) rb - Read Binary mode (To read binary files like images, videos, audio etc) wb - Write Binary mode (To write to binary files) ab - Append Binary mode (To add more binary to the end of a file)

We can use full paths too, such as D:\\testfolder\hello.txt in Windows or /home/harrypotter/Documents/hello.txt in *nix systems (Mac and Linux). Or relative paths ../hello.txt to get a file named hello.txt in the parent directory.

OK, now we try to read from the file. Edit the Python file now:

f = open('test.txt', 'r')
text = f.read()
print(text)

Run, and you should see Hell is empty and all the devils are here. being printed to the console. It's good practice to close a file after you're done working with it:

f = open('test.txt', 'f')
# Do some stuff...
f.close()

Now, to write to a file:

quote_file = open('test.txt', 'w') # Open in write mode.
quote_file.write('All that glitters is not gold.')
quote_file.close()

Done. Now if you open the file with a text editor you should see the new text inside.

Opening in write mode completely overwrites the file, whether you write anything or not.

Let's try append mode to keep the current text and add some more to the end.

# Now we append, just like a list.
file_name = 'test.txt'
f = open(file_name, 'a')
f.write('Fair is foul, and foul is fair: Hover through the fog and filthy air.')
f.close()

f = open(file_name, 'r')
text = f.read()
print(text)
f.close()

"""
All that glitters is not gold. Fair is foul, and foul is fair: Hover through the fog and filthy air.
"""

Auto closing files

If you feel that the method above is too verbose you can:

with open('text.txt', 'r') as f:
    text = f.read()

This automatically closes the file.

The with method is the recommended way of opening files.

OK. Now we know how to manipulate files. You can now do all sorts of cool stuff. I'd say you've learned 75% of Python basics.

Last updated