Topic_4_Read_and_Write_Load_Modules
Topic_4_Read_and_Write_Load_Modules
Today
Loading Modules
Read and store data to .txt and .csv files
Dictionaries
Packages and import
By default, Python only has access to a small number of built-in types and functions
Majority of functions are located in packages or modules
To access a function, the package which contains the function must be imported
with keyword import
All import statements should be done at the top of your python file
from package import name_func : imports only a single function
Great when you only need one function
readbility: those functions are clearly listed in the import statement at top of the
file)
In [4]: from numpy import cos
print(cos(0))
1.0
2.0
2.0
numpy package adds support for large, multi-dimensional arrays and matrices and
large collection of high-level mathematical functions to operate on these arrays
For non-anaconda users, it must be installed first (see below)
from package import ⁎ imports all functions in package
This import statement should be avoided in most cases
don't know where function is from (if you import more than 1 package)
name conflicts: different packages may have the same named-functions
resulting in one being hidden by another
In [6]: from numpy import *
# All functions in the numpy package can be used directly
# Example: cosine function
print(cos(0))
1.0
import numpy as np
Allows any function to be accessed via np.func_name
Standard way most people import; avoids having to write out numpy.
Still obvious where functions come from
In [7]: import numpy
numpy.cos(0) # Functions in numpy are acessed using dot-notation
Out[7]: 1.0
Out[8]: 1.0
x = random.randint(0,10)
randint(start, stop) returns an integer from the specified range, including(!) the stop
Non-built in Packages
You can also install many other open-source
Be careful installing (shady) "stuff from the internet"!
Step 1: pip3 install packagename
Step 2: import packagename
How do you know all these???
I am older than I look
Google/Stackexchange are your friends
<class '_io.TextIOWrapper'>
For this to work: Save any .txt file of your liking to (a) either the same directly as this
.py file or (b) add a subdirectory like I did relative to this .py file.
Best practise is to use name.close() to close file / empty memory. `
Reading functions
read(): reads whole text
readline(): reads next line. Can be called multiple times.
readlines(): reads all lines as list
all functions only work once per file. When the "book is read" you have to open()
it again
Keep them in the same notebook cell as open() to not end up with surprising
outputs
read()
In [11]: # Use one of the two:
absolute_path = "/Users/m_roel/ [ folder omitted ] /Python Programming for E
relative_path = "files/topic_4_1.txt"
f = open(absolute_path)
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
Cell In[11], line 4
2 absolute_path = "/Users/m_roel/ [ folder omitted ] /Python Programmi
ng for Econ/files/topic_4_1.txt"
3 relative_path = "files/topic_4_1.txt"
----> 4 f = open(absolute_path)
6 text = f.read() # This object has reading ability!
7 print(f"\nUsing read() yields a {type(text)}")
File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-
packages/IPython/core/interactiveshell.py:308, in _modified_open(file, *arg
s, **kwargs)
301 if file in {0, 1, 2}:
302 raise ValueError(
303 f"IPython won't let you open fd={file} by default "
304 "as it is likely to crash IPython. If you know what you are
doing, "
305 "you can use builtins' open."
306 )
--> 308 return io_open(file, *args, **kwargs)
readline()
read line by line
In [ ]: f = open("files/topic_4_1.txt")
readlines()
reads file as list of lines (with \n at the end of each)
to get rid of the right \n use str.rstrip(), which not only removes whitespace but
also \n
alternatively, just specify what to remove directly: str.rstrip('\n')
In [ ]: f = open("files/topic_4_1.txt")
lines = f.readlines()
f.close() # Data is already saved to variable. f can be closed.
print("Initially read in lines:", lines)
In [ ]: lines_clean = []
for line in lines:
lines_clean.append(line.rstrip())
lines_clean = []
print(lines_clean)
f.close()
Writing functions
write(): write text to file (either in append/write mode)
writelines(): writes list of text to file
Numbers must be converted to string to be written.
Writing in appending mode ('a').
In [ ]: f = open("files/topic_4_2.txt", 'r') # Let's read original content
print(f"Content of file is: \n {f.read()} \nContent ended.")
f.close()
Dictionaries (dict)
Dictionaries map keys to values
think language dictionary: key is the word you look up, the value is the
translation/explanation
Created using curly brackets, with commas separating entries: dict_1 =
{key_1: value_1, key_2: value_2}
Values are accessed using keys (instead of relying on an numbered index as in lists)
keys must be unique (immutable) data types
e.g., strings, integers, or tuples (containing immutable types)
values can contain any valid Python data type
Dictionaries are mutable
In [ ]: data = {'name': "Marcus",
'favorite fruit': 'xigua',
666: 'juggle 5 balls'}
print(type(data))
# print(data)
In [ ]: # Access data
print(f"Name is {data['name']}")
print(f"... and he can {data[666]}.") # Also, what a show-off!
Edit entries
edit entries (just like lists) by re-assigning a value to an existing key (instead of
location)
In [ ]: data['name'] = "His Highness, the Prince of Genovia"
print(f"His name is now: {data['name']}")
Delete entries
Key-value pairs can be deleted using the reserved keyword del.
In [ ]: del data['favorite fruit']
pprint.pprint(data)
Checking
container if something is part of a list(like) object / data
to check if something is part of something else, use bolean statement x in
object
example: 'name' in data.keys()
In [ ]: if 'name' in data.keys():
print(f"name = {data['name']}")
if 'UNNC' in data.keys():
print(f"UNNC = {data['UNNC']}")
else:
print(f"UNNC is not a valid key")
To see what happens if we try to access a non-valid key, try
print(data['UNNC'])
Appendix
Advanced Features, Code and Use-Cases (non-examinable)
Advanced Syntax: block commands
Use the block command to automatically close the file but retain access to text.
In [ ]: with open("files/topic_4_1.txt") as f:
text = f.read() # Swap with any other (read) command.
print(text) # Text object can be used outside of block-code!