Week 7

File I/O and Numpy Array

File I/O

File I/O (Input/Output) refers to our ability to create / manipulate files via our Python scripts. Though many packages have specific functions for this purpose, Python itself has a convenient set of functions which we can use to manipulate files.

Open and Close

Before we can manipulate files, we need to open or create them. To open a file we use the open() function and store a "link" to the file in a variable:

  • If we want to write to the file: open("file_name", "w")

  • If we want to read from the file: open("file_name", "r")

  • If we want to append to a file: open("file_name", "a")

  • There are more options - see the documentation at https://docs.python.org/3/library/functions.html#open

# Create a file for writing, called "my_file.txt"
new_file = open("my_file.txt", "w")

If a file doesn't exist when we try to open it, then Python will create it

Once we're done with using a file, we call .close() on the file link to close it

# Close the file
new_file.close()

Alternatively, we can use a with statement to open a file, do some immediate manipulation, and then have python automatically close it (i.e. the file link can only be used within the indented statement):

with open("my_file.txt", "r") as f:
    # Do something to the file here
    print("hi")

Write

The simplest way to add to our file is by using the .write() function on the variable containing the file link:

The above example will create the following text file in our working directory (typically the same folder as your python script):

Read

Sometimes we'd rather read the profound works of others than create our own. To this end, we can use

  • .read(n) to read the first n characters

  • .readline() to read the first line

  • .readlines() to read the entire file - stores it as a list, with each line (string) as an element

These read functions step through the parts of the file that have already been read - so calling .readline() twice in succession will read the first two lines of a file

Let's put this to use on some of Gandalf's wise advice:

Supposing the "wisdom.txt" file is in our working directory, we can try reading it:

If you'd like to play around with the read/write functionality, here's the file used in the above example:

238B
Open
Gandalf's wise words to Frodo

Reading with For loops

Most often, we'll just use a for loop to read our file, line by line. Essentially, the for loop is performing:

but we don't need to specify the conversion of the file to a list of lines, as this is the default behavior:

Last updated

Was this helpful?