Arvutiteaduse instituut
  1. Kursused
  2. 2025/26 sügis
  3. Programmeerimise alused (MTAT.03.236)
EN
Logi sisse

Programmeerimise alused 2025/26 sügis

  • Home Page
  • Introduction
  • Expressions
  • Conditional Execution
  • Functions
  • Iterations
  • Strings
  • Files
  • Lists
  • Graphics?
< previousTable of Contentsnext >

7.4 READING FROM FILES

Reading from files allows us to access the contents of the file.

READING THE ENTIRE FILE AT ONCE

We can use the .read() method to read the entire file. It loads the entire content of the file into a single string.

Here's an example in Thonny of how we can use this method.

READING FROM THE FILE LINE BY LINE

The .readline() method reads and returns one line from the file, including the newline character at the end of the line. This enables us to process the file one line at a time without loading the entire file into memory.

Here, we create a while loop to iterate over all the text file lines. We break out of the loop once we've hit the end of the file.

.readlines() method reads all lines in a file and returns them as a list of strings. Each string in the list represents one line from the file. Hence, we’re able to iterate over them with a for loop.

In the context of this course, it’s rather a matter of preference of which method you'd like to use.

KEY THINGS TO REMEMBER

  • In case there is more than one line in the file, we should use a for loop to iterate over all the lines in the file.
  • read() reads the entire content of a file into a single string.
  • readline() reads and returns one line from the file at a time, including the newline character /n at the end of the string.
  • readlines() reads all lines from a file and returns them as a list of strings.

SELF-CONTROL EXERCISES

< previousTable of Contentsnext >

  • Arvutiteaduse instituut
  • Loodus- ja täppisteaduste valdkond
  • Tartu Ülikool
Tehniliste probleemide või küsimuste korral kirjuta:

Kursuse sisu ja korralduslike küsimustega pöörduge kursuse korraldajate poole.
Õppematerjalide varalised autoriõigused kuuluvad Tartu Ülikoolile. Õppematerjalide kasutamine on lubatud autoriõiguse seaduses ettenähtud teose vaba kasutamise eesmärkidel ja tingimustel. Õppematerjalide kasutamisel on kasutaja kohustatud viitama õppematerjalide autorile.
Õppematerjalide kasutamine muudel eesmärkidel on lubatud ainult Tartu Ülikooli eelneval kirjalikul nõusolekul.
Courses’i keskkonna kasutustingimused