2-4 Intro Python Practice

Working with Files

Student will be able to

  • Import files into Jupyter notebooks
  • Open and .read() local files in memory
  • Use .read() to read a specific number of characters
  • Use .readlines() to read data from file as a list of lines
  • Use .readlines() to read data from file as a list of lines
  • Use .readline() to read data from file a line at a time
  • Use .strip() to remove new line characters
  • Use .write() to write data to a new local file
  • Use .seek() to set file read or write location
  • Use file append mode

 

Task 1

Order the Rainbow

Open the rainbow file then put in a list and print in alphabetical order

Download and open the file.

In [1]:
# [ ] import https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/rainbow as rainbow.txt
#Answer:
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/rainbow -o rainbow.txt 
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    43  100    43    0     0    113      0 --:--:-- --:--:-- --:--:--   114
  • Read rainbow_file as a list variable: rainbow_colors using .readlines()
In [2]:
# [ ]  Open rainbow.txt in read mode & read as list with .readlines()
#Answer:

rainbow_file = open('rainbow.txt', 'r')
rainbow_colors = rainbow_file.readlines()
  1. Sort the rainbow_lines list alphabetically.
  2. Print each line of rainbow_lines by iterating the sorted list.
  3. Close rainbow_file.
In [4]:
# [ ] sort rainbow_colors list, iterate the list to print each color
#Answer:

rainbow_colors.sort()
for color in rainbow_colors:
    print(color[:-1])
blue
green
indigo
orange
red
violet
yellow

 

Task 2

The Weather

Create a program that reads from a file to display city name and average temperature in Celsius.

 

In [10]:
# [ ] The Weather: import world_mean_team.csv as mean_temp.txt
#Answer:
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/world_temp_mean.csv -o mean_temp.txt 
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   222  100   222    0     0    781      0 --:--:-- --:--:-- --:--:--   804
  1. Open the file in 'r' mode.
  2. Read the first line of text into a variable called: headings and print().
  3. Convert headings to a list using .split(',') which splits on each comma, print() the list.
In [20]:
# [ ] The Weather: open file, read/print first line, convert line to list (splitting on comma)
#Answer:
world_mean_team_file = open('mean_temp.txt', 'r')
heading = world_mean_team_file.readline()
heading_list = list(heading[:-1].split(','))
#print (world_mean_team_line)
print (heading_list)
['city', 'country', 'month ave: highest high', 'month ave: lowest low']

use a while loop to read the remaining lines from the file

  1. Assign remaining lines to a city_temp variable.
  2. Convert the city_temp to a list using .split(',') for each .readline() in the loop.
  3. Print each city & the highest monthly average temperature.
  4. Close mean_temps.

>Tips & Hints:

  • Use the print output of headings to determine the city_temp indexes to use.
  • "month ave: highest high" for Beijing is 30.9 Celsius.
  • Convert city_temp to lists with .split(',').
In [21]:
# [ ] The Weather: use while loop to print city and highest monthly average temp in celsius
#Answer:
print(heading_list[0],heading_list[2])
while True:
    city_temp = world_mean_team_file.readline()
    if (len(city_temp)==0):
        break
    else:
        city_temp_list = list(city_temp[:-1].split(','))
        print(city_temp_list[0],city_temp_list[2])
city month ave: highest high
Beijing 30.9
Cairo 34.7
London 23.5
Nairobi 26.3
New York City 28.9
Sydney 26.5
Tokyo 30.8

 

Task 3

Random pi guessing

Create random appearing numbers by reading digits of pi Note: only "appears" random

In [23]:
# [ ] use curl to download https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/digits_of_pi as pi.txt
#Answer:
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/digits_of_pi -o pi.txt 
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   303  100   303    0     0   1130      0 --:--:-- --:--:-- --:--:--  1188-:-- --:--:-- --:--:--     0

Set up the project files and intitial values

  1. Open pi.txt in read mode, the file has a single line of text "3.14....".
  2. Get user name as input and say "hi".
  3. Use the length of name for variable called seed.
  4. Use .seek() with the value of seed to set the initial pointer location reading the file.
  5. Create a variable digit and assign it the value of reading one character from the file.
  6. Get guess variable value from users input - "enter a single digit guess or "q" to quit".
  7. Initialize correct and wrong counter variables to 0 (zero).
In [41]:
# [ ] Set up the project files and initial values
#Answer:
pi_file = open("pi.txt",'r')
pi_file.seek(0,0)
pi_text = pi_file.read()
user_name = input('Type your name: ')
print('Hi ',user_name)
seed = len(user_name)
digit = pi_file.seek(seed)
guess = input('enter a single digit guess or "q" to quit')
correct = 0
wrong = 0
print('digit = ',digit,'gues = ',guess)
Type your name: Rachel
Hi  Rachel
enter a single digit guess or "q" to quit6
digit =  6 gues =  6

Create a while loop that tests that guess is a digit string

then in the loop:

  1. if digit ( read from pi file) is "." read the next character for digit
  2. else if digit is "\n" increment seed and use seed to set the pointer uing .seek()
  3. else see if guess is equal to digit
    a. if guess equals digit: print "correct" and increment the varible named correct
    b. if guess not equal digit: print "incorrect" and increment the variable named wrong

end the while loop when user enters any non-digit(s) for guess, like "q".

  • Print correct and wrong values within a message to the user.
  • Close the pi file.
In [42]:
#Answer:
if (digit == "."):
    digit = pi_file.seek(seed+1)
elif (digit == "\n"):
    seed+=1
    digit = pi_file.seek(seed)
if (int(digit) == int(guess)):
    print("correct")
    correct += 1  
else:
    print("wrong")
    wrong += 1
print('digit = ',digit,'gues = ',guess)
print('correct = ',correct," ; incorrect = ",wrong)    
correct
digit =  6 gues =  6
correct =  1  ; incorrect =  0
In [ ]:
 

Terms of use   Privacy & cookies   © 2017 Microsoft