File Reading

Open and Read

  1. # open and read file
  2. file = open("data.txt", "r")
  3. content = file.read()
  4. file.close()

Context Manager (Best Practice)

  1. # with statement
  2. with open("data.txt", "r") as file:
  3. content = file.read()
  4. #ans: file automatically closed

Read Lines

  1. # read all lines
  2. with open("data.txt", "r") as file:
  3. lines = file.readlines()
  4. #ans: returns list of lines

Read Line by Line

  1. # iterate over lines
  2. with open("data.txt", "r") as file:
  3. for line in file:
  4. print(line.strip())

Readline Method

  1. # read one line at a time
  2. with open("data.txt", "r") as file:
  3. line1 = file.readline()
  4. line2 = file.readline()

Read with Limit

  1. # read n characters
  2. with open("data.txt", "r") as file:
  3. content = file.read(10)
  4. #ans: first 10 characters

Exercises - Part 1

  1. # what happens without close?
  2. file = open("data.txt", "r")
  3. content = file.read()
  4. #ans: file remains open (bad practice)

Exercises - Part 2

  1. # read() returns what type?
  2. with open("data.txt", "r") as f:
  3. content = f.read()
  4. #ans: str (string)

Exercises - Part 3

  1. # readlines() returns?
  2. with open("data.txt", "r") as f:
  3. lines = f.readlines()
  4. #ans: list of strings

Exercises - Part 4

  1. # strip() in loop?
  2. for line in file:
  3. print(line.strip())
  4. #ans: removes \n at end

Exercises - Part 5

  1. # read empty file?
  2. with open("empty.txt", "r") as f:
  3. content = f.read()
  4. #ans: "" (empty string)

Exercises - Part 6

  1. # file not found?
  2. with open("missing.txt", "r") as f:
  3. pass
  4. #ans: FileNotFoundError

Exercises - Part 7

  1. # read twice?
  2. with open("data.txt", "r") as f:
  3. c1 = f.read()
  4. c2 = f.read()
  5. #ans: c2 is "" (already at end)

Exercises - Part 8

  1. # readline at end?
  2. with open("data.txt", "r") as f:
  3. f.read()
  4. line = f.readline()
  5. #ans: "" (empty string)

Exercises - Part 9

  1. # iterate multiple times?
  2. with open("data.txt", "r") as f:
  3. for line in f:
  4. pass
  5. for line in f:
  6. pass
  7. #ans: second loop doesn't run

Exercises - Part 10

  1. # read with encoding?
  2. with open("data.txt", "r", encoding="utf-8") as f:
  3. content = f.read()
  4. #ans: specify encoding explicitly

Google tag (gtag.js)