Seite - 122 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
Bild der Seite - 122 -
Text der Seite - 122 -
122 5 SomeMorePythonEssentials
5.5 Files:ReadandWrite
Input data for a program often come from files and the results of the computations
are often written to file. To illustrate basic file handling, we consider an example
where we readx andy coordinates from two columns in a file, apply a functionf
to the y coordinates, and write the results to a new two-column data file. The first
lineof the inputfile is a heading thatwecan just skip:
# x and y coordinates
1.0 3.44
2.0 4.8
3.5 6.61
4.0 5.0
Therelevant Python lines for reading the numbersandwriting out a similar file are
givenin thefilefile_handling.py
filename = ’tmp.dat’
infile = open(filename, ’r’) # Open file for reading
line = infile.readline() # Read first line
# Read x and y coordinates from the file and store in lists
x = []
y = []
for line in infile: # Read one line at a time
words = line.split() # Split line into words
x.append(float(words[0]))
y.append(float(words[1]))
infile.close()
# Transform y coordinates
from math import log
def f(y):
return log(y)
for i in range(len(y)):
y[i] = f(y[i])
# Write out x and y to a two-column file
filename = ’tmp_out.dat’
outfile = open(filename, ’w’) # Open file for writing
outfile.write(’# x and y coordinates\n’)
for xi, yi in zip(x, y):
outfile.write(’{:10.5f} {:10.5f}\n’.format(xi, yi))
outfile.close()
If you have problems understanding the details here, make your own copy and
insertprintoutsoflineand thewordelements in the (first) loop.
Withzip, in thefirst iteration,xiandyiwill represent thefirstelementofxand
y, respectively. In thesecond iteration,xiandyiwill represent thesecondelement
ofxandy, andso on.11
11 Generally,zipallowsrunning overmultiple listsat thesame time,endingwhen theshortest list
isfinished.
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
- Titel
- Programming for Computations – Python
- Untertitel
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Band
- Second Edition
- Autoren
- Svein Linge
- Hans Petter Langtangen
- Verlag
- Springer Open
- Datum
- 2020
- Sprache
- englisch
- Lizenz
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Abmessungen
- 17.8 x 25.4 cm
- Seiten
- 356
- Schlagwörter
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Kategorie
- Informatik