Kodeeksempler
planets = {
'Merkur': (3.2, 88),
'Venus': (6.0, 225),
'Tellus': (8.3, 365),
'Mars': (12.6, 687),
'Jupiter': (43.2, 4333),
'Saturn': (79.3, 10759),
'Uranus': (159.6, 30687),
'Neptun': (246.0, 60190)
}
with open("planeter.txt", "w") as f:
for planet, data in planets.items():
message = f"{planet:>10s} {data[0]:>8.2f} {data[1]:>6d}\n"
f.write(message)
print(message, end="")
# 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