Introduction to Files in Python 3

What’s going on guys?

In this post we’ll do a brief introduction into handling files in Python 3.

We’ll be looking at the following file operations:

  • Opening files for read mode
  • Opening files for write mode
  • Basic file operation functions
  • Reading files in binary mode

This isn’t necessarily an in-depth tutorial, just something to get you started.

Let’s begin!

Python Install and Path Setup

To start off, you should have Python 3 installed on your system. If you don’t, head over to www.Python.org and download the latest version – then install it. I am currently on Python 3.10.2.

You’ll have to add it to your environment path so that you can easily type python and have it executed. Otherwise you’ll run into the following error message:

'python' is not recognized as an internal or external command, operable program or batch file.

For this to work it needs to be in your environment variables. Here’s the instructions:

  1. Press the ‘Windows’ key on your keyboard.
  2. Type ‘environment’, click on the option “Edit the system environment variables.”
  3. Click on the button “Environment Variables” from the System Properties dialog.
  4. Under “System Variables“, select Path and click on Edit.
  5. Then click on New and add the location of your Python installation.

Just for reference, my Python was installed to the following directory:

C:\Users\username\AppData\Roaming\Python\Python310-32\

Note that username will be your computer’s user.

With that out of the way, lets get going with the tutorial.

Open File for Read Mode

Open a command prompt or terminal, then navigate into a directory where you have a text file to open (if you don’t, simply create one using Notepad and write a few lines of text on it for this tutorial).

Once you have the Python interpreter running, let’s open a text file:

file = open("1.txt", 'r')

This will open the file for read mode only. Now to read a line from it:

line = file.readline()
print(line)

This will read a line and print it out on the screen. Note that if you run readline() again, it will read the following line of the text since it keeps track of lines being read.

Now let’s say you only want to read a few characters from the file. You can do that using the read() function and specifying the amount of characters inside the parenthesis. Like so:

line = file.read(6)
print(line)

This will read the first 6 characters from the text file.

You can also seek into different places on that text file using the seek() method.

file.seek(0)

This will go back to the beginning of the file since we’re specifying character 0. You can move thru the file by specifying the position of the character inside the seek function.

The last thing to be aware of when working with files is to remember to close it when you are done:

file.close()

Open File for Write Mode

Now let’s open the file for write mode and write some text in it.

file = open("2.txt", 'w')

This command will open the file for write mode and create the file if it doesn’t exist.

Let’s write some text in the file now:

file.write("Welcome to another Codeonby tutorial!")

This will insert the text in the file and once we close it out it’ll be written to disk.

file.close()

One interesting detail to note when writing to files is we can use the ‘w+’ attribute to add text to a file if we aren’t sure that it already exists or not (most useful inside scripts):

file = open("2.txt", 'w+')
file.write("Cheers")
file.close()

This will add the ‘Cheers’ text to the second line of the file we just wrote previously.

Open File for Read in Binary Mode

To wrap it up, lets open a file for read mode in binary:

file = open("binary.exe", 'rb')

This will open a file in binary read mode, make sure you have a file available in the directory you are in. Let’s proceed by reading 256 bytes from the executable:

byte = file.read(256)
print(byte)

That will read 256 bytes and print them out to the screen.

Don’t forget to close the file on your way out!

That’s it for this tutorial, stay tuned for the next part. 😉

Share: