06-files

ipynb7 kBPython · 16 cellsSlides of chapter 0

Files

Jupyter notebooks

This is a space where text and code come together to form a coherent document. Throughout the course, we will make use of Jupyter notebooks for illustration purposes and for experimentation.

Files

In Python, it is easy to interact with files on your system by opening them and closing them. The general code structure is as follows:

name_handle = open(file_path, mode)

# do some work

name_handle.close()

The first line is responsible for opening a file. In it, the variable file_path is a string containing the address on your machine of the file you need. For example, file_path = “C:/HOME/Desktop/my_file.txt on WindowsOS or file_path = /usr/Desktop/my_file.txt on Linux/MacOS.

As for mode, it is also a string input to the open function used to indicate the mode in which you want to open the file:

  • mode = "r": opens the file in read-only mode.
  • mode = "w": opens the file in write mode.
  • mode = "a": opens the file in append mode.

There are other modes we will not work with.

The open() function returns an object of type _io.TextIOWrapper and stores it in a variable called name_handle.

Read-only mode

In one shot

To read the file contents in one shot, use the .read() method which returns a string containing the text contents of the file.

Example:

In [1]
def read_file(file_path):
    assert type(file_path) == str, "Bad input!"
    
    name_handle = open(file_path, "r")
    s = name_handle.read()
    name_handle.close()
    
    return s
In [2]
address = "my_file.txt" # change this to your own file path
file_contents = read_file(address)
print(file_contents)
Hello from my_file.txt!
This is the second line.
And this is the last line.

Reading the file line by line

You may think of name_handle as a sequence, similar to a list, str, or tuple. Therefore, it is an iterable and one can use a for-loop to iterate over its contents. Specifically, we can iterate over the file contents line by line.

Example:

In [3]
def display_file(file_path, with_line_number=True):
    assert type(file_path) == str, "Bad Input!"
    
    name_handle = open(file_path, "r")
    
    line_number = 1
    for line in name_handle:
        if with_line_number:
            print("Line ", line_number, ": ", line, sep="", end="")
        else:
            print(line, end="")
        line_number += 1
        
    name_handle.close()
In [4]
display_file(address)
Line 1: Hello from my_file.txt!
Line 2: This is the second line.
Line 3: And this is the last line.

Write Mode

Using Python, it is possible to create an empty file using write mode and add contents to it. Example:

In [5]
name_handle = open("new_file.txt", "w")

name_handle.write("this is line 1\n")
name_handle.write("this is ")
name_handle.write("line 2\n")
name_handle.write("last line in file")

name_handle.close()

In the above code, the file new_file.txt was created in the same folder containing this notebook (because a full path was not specified). The .write() method was repeatedly used to write content; notice that the input to this method is a string. The contents of the file are:

this is line 1
this is line 2
last line in file

Append mode

If there's an existing file to which we want to add content, we use the append mode instead of write mode to avoid overwriting its contents. Example:

In [6]
name_handle = open("new_file.txt", "a") # opens the file previously created

name_handle.write("this line was added\n")
name_handle.write("this line is new as well")

name_handle.close()

Now, the contents of the file new_file.txt are:

this is line 1
this is line 2
last line in filethis line was added
this line is new as well

Notice how the string "this line was added" is appended directly next to the old last line from before "last line in file".