2-4.2 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 Remove characters using .strip()
4.3 File Read a line at a time with .readline()
4.4 File .write() with .seek()
4.4 File append mode


> Student will be able to
4.1 Import files in Jupyter Notebooks using the curl command
4.1 open() and .read() local files in memory
4.1 .read() a specific number of characters
4.2 Use .readlines() to read text from files as a list of lines
4.2 Use .close to free system resources
4.3 Use .readline() to read data from file a line at a time
4.3 Use .strip() to remove new line characters
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

.readlines()

view video

File read as a list with .readlines()

converts the lines of a file into a list of strings

poem_lines = poem1.readlines()

 

Examples

In [1]:
# [ ] Run to download file to notebook
!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    151      0 --:--:-- --:--:-- --:--:--   152
In [2]:
# [ ] review and run example
# open address to file
poem1 = open('poem1.txt', 'r')

# readlines and print as a list
poem_lines = poem1.readlines()
poem_lines
Out[2]:
['Loops I repeat\n',
 'loops\n',
 'loops\n',
 'loops\n',
 'I repeat\n',
 'until I\n',
 'break\n']
In [3]:
# [ ] review and run example
for line in poem_lines:
    print(line)
Loops I repeat

loops

loops

loops

I repeat

until I

break

 

Task 1

.readlines()

open the cities file as a list

  1. Import a list of cities using curl
    a. git the list from https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/cities
    b. name the list cities.txt
  2. Open cities.txt in read mode using a variable: cities_file
  3. Read cities_file as a list variable: cities_lines using .readlines()
  4. Print each line of cities_lines by iterating the list
In [4]:
# [ ] import cities
#Answer:
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/cities -o cities.txt
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    56  100    56    0     0    187      0 --:--:-- --:--:-- --:--:--   188
In [5]:
# [ ] open cities.txt as cities_file and read the file as a list: cities_lines
#Answer:
cities_file = open('cities.txt','r')
cities_lines = cities_file.readlines()
In [6]:
# [ ] use list iteration to print each city in cities_lines list
#Answer:
for line in cities_lines:
    print(line)
Beijing

Cairo

London

Nairobi

New York City

Sydney

Tokyo

 

Concepts

working with lists from .readlines()

view video

remove newline characters from lists created using .readlines()

for line in poem_lines:
    poem_lines[count] = line[:-1]
    count += 1

line[:-1] sets the end point at the last character of the string, the result is the '\n' (newline) character is omitted

list item list item contents
poem_lines[0] 'Loops I repeat\n'
poem_lines[1] 'loops\n'
poem_lines[2] 'loops\n'
poem_lines[3] 'I repeat\n'
... ...

 

Examples
This example assumes that poem1.txt has been imported in 1st example above

In [7]:
# [ ] review and run examples
# [ ] re-open file and read file as a list of strings
poem1 = open('poem1.txt', 'r')
poem_lines = poem1.readlines()
print(poem_lines)
['Loops I repeat\n', 'loops\n', 'loops\n', 'loops\n', 'I repeat\n', 'until I\n', 'break\n']
In [8]:
# [ ] print each list item 
for line in poem_lines:
    print(line)
Loops I repeat

loops

loops

loops

I repeat

until I

break

In [9]:
# [ ] remove the last character of each list item, which is "\n"
count = 0

for line in poem_lines:
    poem_lines[count] = line[:-1]
    count += 1

print(poem_lines)
['Loops I repeat', 'loops', 'loops', 'loops', 'I repeat', 'until I', 'break']
In [10]:
# [ ] print each list item 
for line in poem_lines:
    print(line)
Loops I repeat
loops
loops
loops
I repeat
until I
break

 

Task 2

remove newline characters from cities lists created using .readlines()

  • This task assumes that cites.txt has been imported in Task 1 above
  • In task 1, the cities were printed with a blank line between each city - this task removes the blank lines
In [11]:
# [ ] re-open file and read file as a list of strings 
# [ ] open cities.txt as cities_file and read the file as a list: cities_lines
#Answer:
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/cities -o cities.txt
cities_file = open('cities.txt','r')
cities_lines = cities_file.readlines()
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    56  100    56    0     0    302      0 --:--:-- --:--:-- --:--:--   311
In [32]:
# [ ] remove the last character, "\n", of each cities_lines list item 
count = 0
for line in cities_lines:
    cities_lines[count] = line[:-1]
    count += 1

print(cities_lines)
['Beijing', 'Cairo', 'London', 'Nairobi', 'New York City', 'Sydney', 'Tokyo']
In [13]:
# [ ] print each list item in cities_lines
for line in cities_lines:
    print(line)
Beijing
Cairo
London
Nairobi
New York City
Sydney
Tokyo

 

Concepts

.close()

view video

File .close() method frees resources

flie.close() method removes the reference created from file open() function

poem1.close()

 

Examples
This example assumes that poem1.txt has been imported in 1st example above

In [14]:
# [ ] review and run example: open and readlines of poem1.txt
poem1 = open('poem1.txt', 'r')
In [15]:
# [ ] review and run example: readlines breaks if file is no longer open

poem_lines = poem1.readlines()
print(poem_lines)
['Loops I repeat\n', 'loops\n', 'loops\n', 'loops\n', 'I repeat\n', 'until I\n', 'break\n']
In [16]:
# [ ] review and run example: Close poem1
poem1.close()

 

Task 3

File .close()

write each item in it's own cell

  • open cities.txt as cities_file
  • read the lines as cities_lines
  • print the cities that start with the letter "D" or greater
  • close cities_file
  • test that file is closed
In [22]:
# [ ] open cities.txt as cities_file
#Answer:
#Answer:
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/cities -o cities.txt
cities_file = open('cities.txt','r')
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    56  100    56    0     0    260      0 --:--:-- --:--:-- --:--:--   270
In [23]:
# [ ] read the lines as cities_lines
#Answer:
cities_lines = cities_file.readlines()
In [25]:
# [ ] print the cities that start with the letter "D" or greater
#Answer:
print (cities_lines)
for line in cities_lines:
    if(line[0].upper() >= 'D'):
        print(line)
['Beijing\n', 'Cairo\n', 'London\n', 'Nairobi\n', 'New York City\n', 'Sydney\n', 'Tokyo\n']
London

Nairobi

New York City

Sydney

Tokyo

In [26]:
# [ ] test that file is closed
#Answer:
cities_file.close()
In [28]:
# [ ] close cities_file
#Answer:
print("Is CLose: ",cities_file.closed)
Is CLose:  True

 

Task 4

readlines() poem2

write each item in its own cell

In [40]:
# [ ] import https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/poem2.txt as poem2.txt
#Answer:
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/poem2.txt -o poem2.txt
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    57  100    57    0     0    222      0 --:--:-- --:--:-- --:--:--   227
In [41]:
# [ ] open poem2.txt as poem2_text in read mode
#Answer:
poem2_file = open('poem2.txt','r')
In [42]:
# [ ] create a list of strings, called poem2_lines, from each line of poem2_text
#Answer:
poem2_lines = poem2_file.readlines()
In [43]:
# [ ] remove the newline character for each list item in poem2_lines
#Answer:
count = 0
for line in poem2_lines:
    poem2_lines[count] = line[:-1]
    count += 1

print(poem2_lines)
['while True', 'I loop', 'True', 'loop', 'True', 'loop', 'not True', 'False', 'end']
In [44]:
# [ ] print the poem2 lines in reverse order
#Answer:
poem2_lines.reverse()
print(poem2_lines)
['end', 'False', 'not True', 'loop', 'True', 'loop', 'True', 'I loop', 'while True']

Terms of use   Privacy & cookies   © 2017 Microsoft