Page - 122 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 122 -
Text of the Page - 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, Volume Second Edition
- Title
- Programming for Computations β Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Volume
- Second Edition
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2020
- Language
- English
- License
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 356
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik