2-4.3 Intro Python

Working with Files

4.1 File import in Jupyter Notebooks
4.1 File open() and .read()
4.2 File Read as a list with .readlines()
4.2 File Closing to free resources with .close
4.3 File Read, a line at a time with .readline()
4.3 Remove characters using .strip()
4.4 File .write() with .seek()
4.4 File append mode


> Student will be able to
4.1 Import files in Jupyter Notebooks
4.1 open() and .read() local files in memory
4.1 .read() a specific number of characters
4.2 Use .readlines() to read data from file as a list of lines
4.2 Use .close to free system resources
4.3 Use .readline() to read data from file, one line at a time
4.3 Use .strip() to remove new line characters and other whitespaces
4.4 .write() data to a new local file 4.4 Use .seek() to set file read or write location
4.4 Use file append mode

 

Concepts

.readline(): read files a line at a time

view video

use .readline() to read a line in a file as a string

each .readline() moves to the next available line in the file

poem1 = open('poem1.txt', 'r')
poem_line1 = poem1.readline()
poem_line2 = poem1.readline()
poem_line3 = poem1.readline()

 

Examples

In [1]:
# [ ]Run to download file poem1.txt
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/poem1.txt -o poem1.txt 
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    56  100    56    0     0    112      0 --:--:-- --:--:-- --:--:--   113
In [2]:
# [ ] review and run example
# open address to file
poem1 = open('poem1.txt', 'r')
In [3]:
# [ ] review and run example
# readline 1, 2, 3
poem_line1 = poem1.readline()
poem_line2 = poem1.readline()
poem_line3 = poem1.readline()
In [4]:
# [ ] review and run example: print the first 3 .readline() values
print(poem_line1 + poem_line2 + poem_line3)
Loops I repeat
loops
loops

In [5]:
# [ ] review and run example printing return value & re-run several times
print(poem1.readline())
loops

In [6]:
# [ ] review and run example to close file in memory- then run previous cell

poem1.close()

 

Task 1

use readline to get rainbow colors

In [7]:
# [ ] 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    104      0 --:--:-- --:--:-- --:--:--   105
In [8]:
# [ ] open rainbow.txt as rainbow_text

#Answer:
rainbow_text = open('rainbow.txt', 'r')
In [9]:
# [ ] read the first 3 lines into variables: color1, color2, color3

#Answer:
color1 = rainbow_text.readline()
color2 = rainbow_text.readline()
color3 = rainbow_text.readline()
In [10]:
# [ ] close rainbow.txt

#Answer:
rainbow_text.close()
In [11]:
# [ ] print the first 3 colors

#Answer:
print(color1 + color2 + color3)
red
orange
yellow

 

Concepts

.readline() in a while loop

>python poem_line = poem1.readline() while poem_line: print(poem_line.capitalized()) poem_line = poem1.readline()
view video

while .readline()

  • while loop continues while the readline() value in poem_line returns text
    • a string value evaluates as True in the while loop
    • an empty string, '', evaluates not True in the while loop
  • when readline() reaches the end of the file, an empty string is returned

 

Examples

In [12]:
# [ ] review and run example
# open address to file
poem1 = open('poem1.txt', 'r')
In [13]:
# [ ] review and run example - use a while loop to read each line of a file 
#  remove last character ('\n') and print as upper case
poem_line = poem1.readline()

while poem_line:
    print(poem_line[:-1].upper())
    poem_line = poem1.readline()
LOOPS I REPEAT
LOOPS
LOOPS
LOOPS
I REPEAT
UNTIL I
BREAK
In [14]:
# [ ] review and run example
poem1.close()

 

Task 2

while .readline() rainbow colors

assumes rainbow.txt has been imported in task 1

  • open rainbow.txt as rainbow_file as read-only
  • read a color from each line of rainbow_file in a while loop
    • print each color capitalized
  • close rainbow_file
In [19]:
# [ ] open rainbow.txt as rainbow_text as read-only

#Answer:
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/rainbow -o rainbow.txt 
rainbow_text = open('rainbow.txt', 'r')    
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    43  100    43    0     0    127      0 --:--:-- --:--:-- --:--:--   131
In [20]:
# [ ] read the color from lines of rainbow_text in a while loop
# [ ] print each color capitalized as the loop runs

#Answer:
color = rainbow_text.readline()

while color:
    print(color[:-1].upper())
    color = rainbow_text.readline()
RED
ORANGE
YELLOW
GREEN
BLUE
INDIGO
VIOLET
In [21]:
# [ ] close rainbow_text 

#Answer:
rainbow_text.close()

 

Concepts

.readline() with .strip()

view video

.strip() whitespace

poem_line = poem1.readline().strip()

.strip() removes leading and trailing whitespace, including the '\n' formatting character

 

Examples

In [22]:
# [ ] review and run example
# open address to file
poem1 = open('poem1.txt', 'r')
In [23]:
# [ ] review and run example - readline while loop without removing '\n'
poem_line = poem1.readline()

while poem_line:
    print(poem_line)
    poem_line = poem1.readline()

poem1.close()
Loops I repeat

loops

loops

loops

I repeat

until I

break

now with .strip() to remove leading and trailing whitespace characters

In [24]:
# [ ] review and run example - readline with .strip() to remove '\n'
poem1 = open('poem1.txt', 'r')
poem_line = poem1.readline().strip()

while poem_line:
    print(poem_line)
    poem_line = poem1.readline().strip()
    
poem1.close()
Loops I repeat
loops
loops
loops
I repeat
until I
break

 

Task 3

.readline() with .strip() rainbow colors

assumes rainbow.tx has been imported in task 1

  • open rainbow.txt as rainbow_file as read-only
  • read a color from each line of rainbow_file in a while loop
    • use .strip to remove the whitespace
    • print each color upper case
  • close rainbow_file
In [25]:
# [ ] open rainbow.txt as rainbow_text as read-only  

#Answer:
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/rainbow -o rainbow.txt 
rainbow_text = open('rainbow.txt', 'r')    
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    43  100    43    0     0    106      0 --:--:-- --:--:-- --:--:--   107
In [26]:
# [ ] read a color from each line of rainbow_text in a while loop  
# use .strip to remove the whitespace '\n' character 
# print each color upper case 

#Answer:
color = rainbow_text.readline().strip()

while color:
    print(color.upper())
    color = rainbow_text.readline().strip()
RED
ORANGE
YELLOW
GREEN
BLUE
INDIGO
VIOLET

 

Concepts

.strip() with arguments

view video

.strip() arguments

color = rainbow_messy.readline().strip('*\n*')

.strip('*\n') removes leading and trailing * and \n

 

Examples

In [27]:
# [ ] review and run example: import rainbow_messy.txt
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/rainbow_messy -o rainbow_messy.txt
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    71  100    71    0     0    241      0 --:--:-- --:--:-- --:--:--   256
In [28]:
# [ ] review and run example: open file read only
rainbow_messy = open('rainbow_messy.txt', 'r')
In [29]:
# [ ] review and run example: .readline() without .strip()

color = rainbow_messy.readline()

while color:
    print(color)
    color = rainbow_messy.readline()
**red**

**orange**

**yellow**

**green**

**blue**

**indigo**

**violet**

In [30]:
# [ ] review and run example: strip "*" and newline ('\n')
rainbow_messy = open('rainbow_messy.txt', 'r')

color = rainbow_messy.readline().strip('*\n')

while color:
    print(color)
    color = rainbow_messy.readline().strip('*\n')

rainbow_messy.close()
red
orange
yellow
green
blue
indigo
violet

 

Task 4

.strip() with arguments

  • run import of cities_messy.txt below at least once this notebook session
  • run open cities_messy.txt below before each test of the while loop cell
  • edit while loop to strip the colon ':' , newline and spaces
  • close cities_messy
In [43]:
# [ ] import the file
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/cities_messy -o cities_messy.txt
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    77  100    77    0     0    271      0 --:--:-- --:--:-- --:--:--   277
In [44]:
# [ ] run to read the file into memory
cities_messy = open('cities_messy.txt', 'r')
In [45]:
# [ ] edit the code to remove leading or trailing colon, newline and space characters
line = cities_messy.readline().strip(" :\n")

while line:
    print(line)
    line = cities_messy.readline().strip(" :\n")
Beijing
Cairo
London
Nairobi
New York City
Sydney
Tokyo

 

Task 5

.strip() parentheses from poem2_messy

In [54]:
# [ ] import https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/poem2_messy as poem2_messy.txt  

#Answer:
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/poem2_messy -o poem2_messy.txt 
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    75  100    75    0     0    344      0 --:--:-- --:--:-- --:--:--   362
In [55]:
# [ ] open poem2_messy.txt as poem2_messy in read mode

#Answer:
poem2_messy = open('poem2_messy.txt', 'r')
In [56]:
# [ ] edit while loop to strip the leading and trailing parentheses, and newlines
# [ ] print the poem 

#Answer:

line = poem2_messy.readline().strip("()\n")

while line:
    print(line)
    line = poem2_messy.readline().strip("()\n")
while True
I loop
True
loop
True
loop
not True
False
end

Terms of use   Privacy & cookies   © 2017 Microsoft