Python Reading from / Writing to Text Files

Read file

Reading a file and print each line

Often you will want to read in data from a text file and do something with each line of data. For this we can use the in-built open function.

Let’s say we have text file that contains 3 words, one on each line. We can use open() to read the file contents into Python

We can load this file and print out each line in the file:

Code

f  = open('animals.txt','r')
for animal in f:
    print(animal.strip('\n'))

Output

cat dog mouse
  • Note how when we open a file for reading we use ‘r’ read mode.

Reading a single line file

If your file only has a single line and you want to read it in, then use readline()

f = open('highscore.txt','r')
high_score = f.readline()
print('High Score:',high_score)

Read to list

Reading data from a text file into a list

Most of the time you will want to read the file into a list. This is simple and easy to achieve:

f  = open('animals.txt','r')

animal_list = []

for animal in f:
    animal_list.append(animal.strip('\n'))

print(animal_list)

Output:

['cat', 'dog', 'mouse']

Write

Writing to Text Files

Sometimes we want to save data to a file. Here we open the file in ‘w’ write mode and use the write() method.

f = open('birds.txt','w')
birds = ["robin","sparrow","eagle"]

for bird in birds:
    f.write(bird + '\n')

f.close()

Output file:

Notes

  • If you want to completely overwrite any data previously saved into the file use ‘w’. If you just want to append(add) to the existing contents of the file use ‘w’
  • make sure you call f.close() after you have finishing writing all the data otherwise it won’t save the changes.

 

Videos

Pros & Cons

Pro & Cons of text files

It is great for storing:

  • Variables (like strings and integers)
  • Simple 1-dimensional lists (such as a shopping list)

It is not good for:

Challenge 33

Challenge 33 – Password Checker

Bronze

 Read in the list of 100 most common passwords from the file passwords.txt into a list called common_passwords.

Silver

 Ask the user to input a test password and let them know if their password is in the list.

Gold

  Get your program to repeat asking the user to enter a password until it is not in the list of common password

34

Challenge 34 – Shopping List Saver

Bronze

  Write a program that asks the user to enter 10 items to add a list called shopping.

Silver

  Get the program to save the list to a text file called shopping.txt

Gold

  Adapt the program so that the program keeps adding items to the shopping list until the user inputs an empty string.

35

Challenge 35 – Square Numbers

Bronze

  Write a program that reads in a list of numbers from the file numbers.txt and a list called numbers

Silver

  For each number it should calculate the square of the number and add the square of the number to a list called squares.

Gold

  The program should then write the square numbers to a text file called square_numbers.txt.

36

Challenge 36 – 💚 Handling non-ASCII characters 💚

Resources

 Bronze

 Write a program that reads the following non-ASCII character file into python and prints out the list of words/emojis. You will need to set the encoding to UTF8 when opening the file  e.g.  f = open(“eg.txt , “r”, encoding = “utf-8”)

Silver

  For the first character in each  line print out the character Unicode value , using the ord() function.

Gold

  Add Unicode emoji art to your python program to make it look 😻😻😻bling-tastic 😻😻😻