File I/O
Overview
Teaching: 10 min
Exercises: 5 minQuestions
How can I read data from a file?
How can I write data to a file?
Objectives
Use
open,read, andreadlineto read data from a file.Use a file in
forloop.Use
writeto save data to a file.Use basic string operations to process text data.
Use open to open files for reading or writing.
- Arguments are a path and:
- ‘r’ for reading
- ‘w’ for writing (immediately erases existing contents)
- ‘a’ for appending
- Result is an object with methods for reading and writing.
file.read()reads the entire file.file.read(N)reads up to that many bytes.
- Close files with
file.close.
reader = open('myfile.txt', 'r')
data = reader.read()
reader.close()
print('file contains', len(data), 'bytes')
file contains 47189 bytes
Usually read text files with for loops.
- Automatically calls
file.readline.
reader = open('myfile.txt', 'r')
count = 0
for line in reader:
count = count + 1
reader.close()
print('file contains', count, 'lines')
file contains 261 lines
Python preserves end-of-line newlines.
- By default, converts Windows ‘\r\n’ to Unix ‘\n’.
Strip whitespace using string methods.
- Use
str.stripto strip leading and trailing whitespace.' abc '.strip()is'abc'.
- Use
str.rstriporstr.lstripto strip space from right or left end only. - All of these methods return new strings.
- Because strings cannot be modified in place.
reader = open('myfile.txt', 'r')
count = 0
for line in reader:
line = line.strip()
if len(line) > 0:
count = count + 1
reader.close()
print('file contains', count, 'non-blank lines')
file contains 225 non-blank lines
Using
withto Guarantee a File is ClosedIt is good practice to
closea file after you have opened it. You can use thewithkeyword in Python to ensure this:with open('myfile.txt', 'r') as reader: data = reader.read() print('file contains', len(data), 'bytes')The
withstatement has two parts: the expression to execute (such as opening a file) and the variable that stores its result (in this case,reader). At the end of thewithblock, the file that was assigned toreaderwill automatically be closed.withstatements can be used with other kinds of objects to achieve similar effects.
Squeezing a File
Write a small program that reads lines of text from a file called
input.datand writes those lines to a file calledoutput.dat.Modify your program so that it only copies non-blank lines.
Modify your program again so that a line is not copied if it is a duplicate of the line above it.
Compare your implementation to your neighbor’s. Did you interpret the third requirement (copying non-duplicated lines) the same way?
Key Points
Open a file for reading or writing with
open.Use
readorreadlineto read directly.Use file in
forloop to process lines.Use
writeto add data to a file.