Locked lesson.
About this lesson
Exercise files
Download this lesson’s related exercise files.
Reading and Writing Files.docx60.6 KB Reading and Writing Files - Solution.docx
59.4 KB
Quick reference
Reading and Writing Files
Once open, you can easily read a file or write to a file.
When to use
Whenver you need to read the contents of a file or write to a file, you'll do it this way.
Instructions
To read and write to a file we use the read() and write() functions.
To read a file:
my_file = open("names.txt", "r") # open a file
my_string = my_file.read() #read that file into a string
To write to a file:
my_file = open("names.txt", "a+") # open the file in append mode
my_file.write("Steve\n") # write Steve to the end of the file with a line break
Hints & tips
- my_file = open("names.txt", "a+) # open a file
- my_string = my_file.read() #read that file into a string
- my_file.write("Steve\n") # write Steve to the end of the file with a line break
Lesson notes are only available for subscribers.