<jupyter_start><jupyter_text>Working with FilesWe will look at several ways to read/write files. For your last project, you will only need to read from a file.<jupyter_code>import os
import json
import csv<jupyter_output><empty_output><jupyter_text>Don't use Pickle!Python contains a file reading/writing library that has been around for years. It is a security risk. Don't use it - especially if you are sharing files with other systems. Malicious code can be embedded in these files.  ExceptionsCatching errors (called exceptions in many programming languages) is useful when you can get bad input from the user. One common example is trying to open a file that doesn't exist.<jupyter_code>read_pm_data('america_pm.txt')
def read_pm_data(filename):
    with open(filename, mode='r') as pm_data:
        for record in pm_data:
            fname, lname, years = record.split()
            print(f'{lname}, {fname}: {years}')
def read_pm_data(filename):
    try:
        with open(filename, mode='r') as pm_data:
            for record in pm_data:
                fname, lname, years = record.split()
                print(f'{lname}, {fname}: {years}')
    except FileNotFoundError:
        print('The filename you have specified does not exist')
num1 = int(input("Enter an integer (-1 to quit): "))

while num1>=0:

    num2 = int(input("Enter a second integer"))
    try:
        print(num1/num2)

    except ZeroDivisionError:
        print("Cannot divide by zero")
        
    num1 = int(input("Enter an integer (-1 to quit): "))
try:
    import mypackage
except ModuleNotFoundError:
    print("This module is not available on this system")    
import mypackage<jupyter_output><empty_output><jupyter_text>Working with CSV files<jupyter_code>with open('prime_ministers.csv', mode='w', newline='') as pm:
    writer = csv.writer(pm)
    writer.writerow(['Stephen','Harper','2006-2015','CA'])
    writer.writerow(['Paul','Martin','2003-2006','CA'])
    writer.writerow(['Jean','Chretien','1993-2003','CA'])
    writer.writerow(['Kim','Campbell','1993-1993','CA'])
    writer.writerow(['Brian','Mulroney','1984-1993','CA'])
    writer.writerow(['John','Turner','1984-1984','CA'])
    writer.writerow(['Mohamad','Mahathir','2018-2020','MA'])
    writer.writerow(['Raza','Najib','2009-2018','MA'])
    writer.writerow(['Badawi','Abdullah','2003-2009','MA'])
    writer.writerow(['Mohamad','Mahathir','1981-2003','MA'])
    writer.writerow(['Onn','Hussein','1976-1981','MA'])       
with open('prime_ministers.csv', mode='r', newline='') as pm:
    reader = csv.reader(pm)
    for record in reader:
        fname, lname, years, country = record
        if(country=='CA'):
            print(fname + ' ' + lname + ', ' + years)<jupyter_output><empty_output><jupyter_text>Working with Pandas<jupyter_code>import pandas as pd
import numpy as np
data = pd.read_csv('prime_ministers.csv', header=None)  #This is a dataframe
data.columns = ['fname','lname','years','country']
start = np.array([int(y[:4]) for y in data['years']])
end = np.array([int(y[5:9]) for y in data['years']])
end - start
data['term_length'] = end -start
len(data)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1514095660437124, 'fraction_numerical': 0.031675641431738996, 'mean_word_length': 4.307563025210084, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 18, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '401074', 'license': 'CNRI-Python', 'n_tokens_mistral': 1086, 'n_tokens_neox': 983, 'n_words': 267, 'path': '11.4.20-ClassSession.ipynb', 'repo_name': 'r2klabs/CS150-InClass', 'size': '3157'}