Reading data from text files#

We have been reading various values from text files using the pathlib Path read_text method, and then processing the lines in the file.

Here is some revision on how to do that, going from the crude to the elegant way.

First we write a little text file out to disk:

from pathlib import Path

numbers = [1.2, 2.3, 3.4, 4.5]
strings = []
for number in numbers:
    # String version of number.
    strings.append(str(number))

# Stick the strings together separated by new lines ('\n'):
out_text = '\n'.join(strings)
out_text
'1.2\n2.3\n3.4\n4.5'
# Write text to file.
path = Path('some_numbers.txt')
path.write_text(out_text)
15

Now we read it back again. First, we will read the all the lines as one long string, then split it into lines at newline characters:

text_back = path.read_text()
lines = text_back.splitlines()
len(lines)
4
lines[0]
'1.2'

Next we will convert each number to a float:

numbers_again = []
for line in lines:
    numbers_again.append(float(line))
numbers_again
[1.2, 2.3, 3.4, 4.5]

In fact we read these data even more concisely, and quickly, by using np.loadtxt.

import numpy as np
np.loadtxt('some_numbers.txt')
array([1.2, 2.3, 3.4, 4.5])

Finally, for neatness, we delete the temporary file:

path.unlink()