Lærebok, kapittel 9.3:
File Objects
# Halterman, R. L, 2019. Fundamentals of Python Programming
#
# Listing 9.5: simplefileread.py
f = open('planeter.txt') # f is a file object
for line in f: # Read each line as text
print(line[0:-1]) # Remove trailing newline character
f.close() # Close the file
# Halterman, R. L, 2019. Fundamentals of Python Programming
#
# Listing 9.6: simplerread.py
with open('planeter.txt') as f: # f is a file object
for line in f: # Read each line as text
print(line[0:-1]) # Remove trailing newline character
# No need to close the file
# Varianter av open-kommandoen
open('planeter.txt') # standard-valg
# - åpner fil for lesing
open('planeter.txt', 'r') # åpner fil for lesing
# - eksplisitt uttrykt
open('planeter.txt', 'w') # åpner fil for skriving
# - sletter eventuell eksisterende fil
open('planeter.txt', 'a') # åpner fil for skriving
# - legger nytt innhold til eksisterende
# angir tegnsett - viktig for å behandle norske tegn
open('planeter.txt', 'a', encoding='utf-8')