Revise Computingrevisecomputing.co.uk
At a glanceFeaturesStudentsPricingHow it worksFree GCSE notesExam dates
At a glanceFeaturesStudentsPricingHow it worksFree GCSE notesExam dates

Knowledge organisers / File Handling Techniques

Reading files

All topicsPractise exam questions
Knowledge organiser

File Handling Techniques

301.15b

Read lines or whole file.

What you need to know

You can read a whole file at once with .read(), get a list of lines with .readlines(), or loop through line by line with a for loop. Each line includes a newline character.

Key points

  • .read() returns the entire file as one string
  • .readlines() returns a list of lines
  • for line in f: loops one line at a time
  • Use .strip() to remove trailing newline from each line

Code examples

Reading lines
python
with open("names.txt", "r") as f:
    for line in f:
        name = line.strip()
        print("Hello, " + name)