Python Read File: read(), readline() and Lines
Read a Whole File with read()
The read() method gives you the whole file as one string. Every line is in it, with a "\n" wherever a line ends.
Think of it like reading a whole letter in one go, instead of one sentence at a time. You get everything at once, and then you can do what you like with it.
The rules
- Open the file in mode
"r"(or with no mode), then callf.read(). - It gives back a string, so store it:
text = f.read(). - Every string method from chapter 12 works on it:
upper(),count(),replace(),split()... - An empty file gives back
"", the empty string.
f = open("poem.txt", "w")
f.write("Roses are red\n")
f.write("Violets are blue\n")
f.close()
f = open("poem.txt", "r")
text = f.read()
f.close()
print(text)
print(len(text))
print(text.count("are"))Roses are red Violets are blue 31 2
len(text) is 31: 29 letters and spaces, plus the two "\n" characters. Yes, a newline counts as a character. And there's an empty line after the poem: the file's last "\n", then the new line print() adds.
Reading a second time
A file remembers how far you've read, like a bookmark. After read(), the bookmark is at the very end. So a second read() finds nothing left:
f = open("poem.txt", "w")
f.write("Roses are red")
f.close()
f = open("poem.txt")
first = f.read()
second = f.read()
f.close()
print(first)
print(len(second))Roses are red 0
Good: read once, keep it
Store the text in a variable and use the variable as often as you like. To read the file from the start again, close it and open it again.
Common beginner doubt: "Is read() OK for a big file?" For the small text files in this course, yes. A huge file would fill your computer's memory, and then you'd read it line by line. That's two lessons from now.
read() gives you the whole file as one string, newlines and all. Read once and keep it.