# read whole file
with open('sample_text.txt', 'r') as f:
contents = f.read()
# read lines and store in a list
with open('sample_text.txt') as f:
lines = f.readlines()
Each task below is interactive. Edit the code in the editor and click Run.
Open wrestlers.txt using the read() method and print its contents.
Editing the code above, change the read() method to readlines() and print each line.
If you print the lines list, you will see each line of the file as a separate item in the list.
You can also use a for loop to iterate over the lines list and print each line individually.
For example:
for line in lines:
print(line)
You can print individual lines if you use the readlines() method.
For example:
lines = f.readlines()
print(lines[0]) # prints the first line
Open wrestlers.txt using the readlines() method and print line 0 and 2
Here you will use the randint function from the random module to select a random line from the file.