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.
open to open files for reading or writing.file.read() reads the entire file.file.read(N) reads up to that many bytes.file.close.reader = open('myfile.txt', 'r')
data = reader.read()
reader.close()
print('file contains', len(data), 'bytes')
file contains 47189 bytes
for loops.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
str.strip to strip leading and trailing whitespace.
' abc '.strip() is 'abc'.str.rstrip or str.lstrip to strip space from right or left end only.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.