Python Data Files Practice Tasks

See notes for Python text files before trying these practice exercises.


Excercise 1

Create a new text file. Use the open() function, and give it a “.txt” file extension. You will need the ‘w’ option as your second parameter, right after the filename. This makes the file writable.

Add a sentence to the file using the write() function. Include “\n” at the end of the sentence so the next text will go on a new line.

Add two more lines of text to the file.

Click the new file to see if your text appears as expected.

Exercise Set 2

Download this text file and put it in your working directory.
(do not copy and paste the data into a python program)

dognames.txt

a) Load the file and create a loop that prints each dog name on a separate line. You will need to use open(), read() or readlines() and a for loop.

b) Create another program that opens the file and prints how many names are in the file. Use len().

c) For your next program, you will write a program that counts how many of the names are 5 letters long or less and how many are at least 6 letters long. Start the program by creating variables that will keep track of the total number of names found so far. For example:

small_names = 0
big_names = 0

This program will need each of the following elements:

  • for loop to iterate through the file’s lines of text
  • if/else structure inside the for loop that checks name length
  • len() function to return the number of in a string
  • strip() function to remove the line breaks from each line

d) In a new program, read the names file and create a new list that contains only dog names that end with the letter “y” and save that list in a new text file with a different name. Use string slicing to find the last letter of the names.