I don’t know if you have ever experienced the need txt
to read data containing multiple rows and multiple columns from a file. When we read in the data, the data will string
be read in the form of, but how to convert the data type becomes a big problem . Here is one of the simplest ways and easy to use wrong method.
txt
The data in the test file is as follows:
We use the following code to read the file and read readlines()
all the data at once.
with open(r"C:\Users\15025\Desktop\debug1.txt", "r") as f:
all_data = f.readlines()
print(all_data)
# ['6.317438621610765E-05 6.123920173773844E-05 0.00010382572761752979\n', '0.00010819194873178063 8.848784016828921E-05 0.0002043378699454479\n', '9.79660835582763E-05 9.750829986943346E-05 0.00021506758227284687']
It is not difficult to find that at this time all our data has been read into the same line, but there are three parts enclosed in single quotes, which are consistent with the three lines in our test data. We can also see that we need to separate these data into separate ones string
, and then we can use for example float
keywords to perform type conversion on these data. We see that the data is separated by spaces. We first thought that we should use a .split(" ")
method to separate the data with spaces. We try the following code:
with open(r"C:\Users\15025\Desktop\debug1.txt", "r") as f:
all_data = f.readlines()
all_data = all_data[0].split(" ")
print(all_data)
# ['6.317438621610765E-05', '', '6.123920173773844E-05', '', '0.00010382572761752979\n']
First we need to select the first row, use all_data[0]
, and then split(" ")
separate them in the use function. We can achieve the goal, but we also introduced the ""
empty string item and \n
the hidden danger at the end , which is very tricky. In doing so, we have entered a misunderstanding. The correct approach is as follows:
with open(r"C:\Users\15025\Desktop\debug1.txt", "r") as f:
all_data = f.readlines()
all_data = all_data[0].split()
print(all_data)
# ['6.317438621610765E-05', '6.123920173773844E-05', '0.00010382572761752979']
We split()
do not add any parameters when using the function, so that the ""
empty string items and \n
hidden dangers at the end are removed at one time and each string is separated at the same time. If you need to output multiple rows of results, we can predefine an array to store our data, the complete code is as follows: (all data can be read in this way)
import matplotlib.pyplot as plt
import numpy as np
array = np.zeros((3, 3))
with open(r"C:\Users\15025\Desktop\debug1.txt", "r") as f:
all_data = f.readlines()
for i, line in enumerate(all_data):
numbers = line.split()
for j, element in enumerate(numbers):
array[i, j] = float(element)
print(array)
# [[6.31743862e-05 6.12392017e-05 1.03825728e-04]
# [1.08191949e-04 8.84878402e-05 2.04337870e-04]
# [9.79660836e-05 9.75082999e-05 2.15067582e-04]]
If you find it useful, please raise your hand to give a like and let me recommend it for more people to see~