Read all the characters into a string (slurp)
- read
In some other cases, especially if you are looknig for some pattern that starts on one line but ends on another line.
you'd be better off having the whole file as a single string in a variable. This is where the read
method comes in handy.
It can also be used to read in chunks of the file.
filename = 'examples/files/numbers.txt'
with open(filename, 'r') as fh:
content = fh.read() # reads all the lines into a string
print(type(content))
print(len(content)) # number of characters in file
print(content) # the content of the file
Output:
<class 'str'>
26
23 345 12345
67 189 23 17
read(20) will read 20 bytes.