Opening Files in Python



Interactive tasks (trinket.io)

Each task below is interactive. Edit the code in the editor and click Run.

Task 1 — Read the contents of the file

Open wrestlers.txt using the read() method and print its contents.

Task 2 — Read the contents of the file as a list

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:

Task 3 — Read the contents of the file and print 1 line only

You can print individual lines if you use the readlines() method.

For example:

Open wrestlers.txt using the readlines() method and print line 0 and 2

Task 4 — A last practice task for you

Here you will use the randint function from the random module to select a random line from the file.