1.9. Modules and Files#

Reference: Chapter 3 of Computational Nuclear Engineering and Radiological Science Using Python, R. McClarren (2018)

1.9.1. Learning Objectives#

After studying this notebook, completing the activities, and asking questions in class, you should be able to:

  • Import functions from modules.

  • Open, read, write to, and close files.

1.9.2. Modules#

Sometimes we have to define many functions and don’t want to have one giant source file (in fact this is good programming practice). To this point, modules are files with the ‘.py’ extension that can be imported into other python programs. I’ve created a file called sphere.py. This file defines two functions volume and surface_area that compute the volume and surface area of a sphere. Because the file is called sphere.py we can import those functions using import sphere. The text of sphere.py is

def volume(radius): """compute volume of a sphere
Args:
radius: float giving the radius of the sphere

Returns:
volume of the sphere as a float
"""
return 4.0/3.0*math.pi*radius**3

def surface_area(radius): “””compute surface area of a sphere

Args:
radius: float giving the radius of the sphere

Returns:
surface area of the sphere as a float
"""
return 4.0*math.pi*radius**2
import sys
sys.path.append('../data') # this opens the correct folder where the system module is so we can import it
import sphere

Now that I have imported the module, we can use help to see the docstring.

help(sphere)
Help on module sphere:

NAME
    sphere

FUNCTIONS
    surface_area(radius)
        compute surface area of a sphere
        
        Args:
        radius: float giving the radius of the sphere
        
        Returns:
        surface area of the sphere as a float
    
    volume(radius)
        compute volume of a sphere
        
        Args:
        radius: float giving the radius of the sphere
        
        Returns:
        volume of the sphere as a float

FILE
    c:\users\ebrea\documents\github\data-and-computing\notebooks\data\sphere.py
r = 1.0
print("The volume of a sphere of radius",r,"cm is",
      sphere.volume(r),"cm**3")
print("The surface area of a sphere of radius",r,"cm is",
      sphere.surface_area(r),"cm**2")
The volume of a sphere of radius 1.0 cm is 4.1887902047863905 cm**3
The surface area of a sphere of radius 1.0 cm is 12.566370614359172 cm**2

1.9.3. Files#

It is very easy to read in text files in python. The file fifth_republic.txt, lists the presidents of France’s fifth republic. It is in the same folder as this notebook.

In Python, we can read it in very simply:

file = open('https://raw.githubusercontent.com/ndcbe/data-and-computing/main/notebooks/data/fifth_republic.txt', 'r') 
#open fifth_republic.txt for reading ('r')
for line in file:
    # Repeat the first 5 characters 3 times
    print(line[0:5]*3)
file.close()
CharlCharlCharl
GeorgGeorgGeorg
ValéValéValé
FranÃFranÃFranÃ
JacquJacquJacqu
NicolNicolNicol
FranÃFranÃFranÃ
EmmanEmmanEmman

Notice how the for loop can iterate through each line of the file. You can also read a line at a time.

file = open('https://raw.githubusercontent.com/ndcbe/data-and-computing/main/notebooks/data/fifth_republic.txt', 'r')
#open fifth_republic.txt for reading ('r')

# Read the first line
first_line = file.readline()

# Read the second line
second_line = file.readline()
print(first_line)
print(second_line)
file.close()
Charles de Gaulle

Georges Pompidou
help(file.readline)
Help on built-in function readline:

readline(size=-1, /) method of _io.TextIOWrapper instance
    Read until newline or EOF.
    
    Returns an empty string if EOF is hit immediately.

You can also easily write to a file.

writeFile = open("https://raw.githubusercontent.com/ndcbe/data-and-computing/main/notebooks/data/hats.txt","w") 
#open hats.txt to write (clobber if it exists)
hats = ["fedora","trilby","porkpie",
        "tam o'shanter","Phrygian cap","Beefeaters' hat","sombrero"]
for hat in hats:
    writeFile.write(hat + "\n") #add the endline
writeFile.close()

#now open file and print
readFile = open("https://raw.githubusercontent.com/ndcbe/data-and-computing/main/notebooks/data/hats.txt","r")
for line in readFile:
    print(line)
readFile.close()
fedora

trilby

porkpie

tam o'shanter

Phrygian cap

Beefeaters' hat

sombrero

We can also use enumerate with a text file: (for more on enumeration see notebook 05-Python-Basics-III)

import csv
file = open('https://raw.githubusercontent.com/ndcbe/data-and-computing/main/notebooks/data/fifth_republic.txt', 'r')
for i,row in enumerate(file):
    print(row)
Charles de Gaulle

Georges Pompidou

Valéry Giscard d'Estaing

François Mitterrand

Jacques Chirac

Nicolas Sarkozy

François Hollande

Emmanuel Macron