Skriving til fil og lesing fra fil

Kodeeksempler

In [11]:
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="")
    Merkur     3.20     88
     Venus     6.00    225
    Tellus     8.30    365
      Mars    12.60    687
   Jupiter    43.20   4333
    Saturn    79.30  10759
    Uranus   159.60  30687
    Neptun   246.00  60190
In [12]:
# 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
    Merkur     3.20     88
     Venus     6.00    225
    Tellus     8.30    365
      Mars    12.60    687
   Jupiter    43.20   4333
    Saturn    79.30  10759
    Uranus   159.60  30687
    Neptun   246.00  60190
In [13]:
# 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
    Merkur     3.20     88
     Venus     6.00    225
    Tellus     8.30    365
      Mars    12.60    687
   Jupiter    43.20   4333
    Saturn    79.30  10759
    Uranus   159.60  30687
    Neptun   246.00  60190