# open and read filefile = open("data.txt", "r")content = file.read()file.close()
# with statementwith open("data.txt", "r") as file: content = file.read()#ans: file automatically closed
# read all lineswith open("data.txt", "r") as file: lines = file.readlines()#ans: returns list of lines
# iterate over lineswith open("data.txt", "r") as file: for line in file: print(line.strip())
# read one line at a timewith open("data.txt", "r") as file: line1 = file.readline() line2 = file.readline()
# read n characterswith open("data.txt", "r") as file: content = file.read(10)#ans: first 10 characters
# what happens without close?file = open("data.txt", "r")content = file.read()#ans: file remains open (bad practice)
# read() returns what type?with open("data.txt", "r") as f: content = f.read()#ans: str (string)
# readlines() returns?with open("data.txt", "r") as f: lines = f.readlines()#ans: list of strings
# strip() in loop?for line in file: print(line.strip())#ans: removes \n at end
# read empty file?with open("empty.txt", "r") as f: content = f.read()#ans: "" (empty string)
# file not found?with open("missing.txt", "r") as f: pass#ans: FileNotFoundError
# read twice?with open("data.txt", "r") as f: c1 = f.read() c2 = f.read()#ans: c2 is "" (already at end)
# readline at end?with open("data.txt", "r") as f: f.read() line = f.readline()#ans: "" (empty string)
# iterate multiple times?with open("data.txt", "r") as f: for line in f: pass for line in f: pass#ans: second loop doesn't run
# read with encoding?with open("data.txt", "r", encoding="utf-8") as f: content = f.read()#ans: specify encoding explicitly
Google tag (gtag.js)