Our "source.txt" is simple, just three lines.
Use "f" as handle for operation. We will just read()
all lines, so "r" is second argument:
f = open("source.txt", "r")
result = f.read()
print(result)
Result:
first line
second line
third line
>>>
If you need to read just specific number of bytes, you can pass that as argument:
f = open("source.txt", "r")
print(f.read(5))
print(f.read(5))
print(f.read(5))
Result:
first
line
seco
>>>
For loops are also great here:
f = open("source.txt", "r")
for x in range(3):
print(f.read(6))
Result:
first
line
s
econd
>>>
With function readline()
we can read line by line:
f = open("source.txt", "r")
print(f.readline())
print(f.readline())
print(f.readline())
Result:
first line
second line
third line
>>>
If you need to extract all lines to list, use readlines()
function:
f = open("source.txt", "r")
all_lines = f.readlines()
print(all_lines)
print(type(all_lines))
Result:
['first line\n', 'second line\n', 'third line\n']
<class 'list'>
>>>
Then we can target individual lines as elements:
f = open("source.txt", "r")
all_lines = f.readlines()
print(all_lines[0])
print(all_lines[1])
print(all_lines[2])
Result:
first line
second line
third line
>>>
Easy.
It't time to learn how to write and append to files.
No comments:
Post a Comment