Skip to main content

Exercise 27: Solution


"""
Exercise 27 - read and write data
Read in the file vector1.txt into a list of floats.
Double the values in the list
Write the new data in a file so that
each value in the list is on an individual line.
Authors: Lauren Gregoire and Caroline Prescott
"""
filename="vector1.txt"
# initialise an empty data array
data=[]
# open file
f=open(filename, 'r')
# Read each line and append the data as a float into the array data
for line in f:
    data.append(float(line))
f.close()
# double the data
# list comprehensions are ideal in this case
data2=[i*2 for i in data]
# format the data for printing (eg. strings with new line characters)
out_data=[]
for x in data2:
    out_data.append(str(x)+"\n")
# write the output to a new file
fout=open('data2.txt','w')
fout.writelines(out_data)
fout.close()