I have a text file with the following information.
document.txt:
z
-0.01,0.04,-0.04,0,-0.06,-0.08,0.04,0.03
z
0.1,-0.02,0.1,0.14,0.07,0.05,0.01
z
0.05,0.05,0.12,0.13,0.08,0.01,0.12,0.11
Essentially, I want my python program to extract the numbers between the markers z
and add it to a list. So there will be 3 lists, the first will contain the numbers between the first and second z
, the second list will contain the numbers between the second and third z
etc...
Here is what I have so far that takes all the numbers, converts them to floats and puts it in a list. Now I need to split it into lists that only contain the numbers between the marker, z.
f = open(file_name)
contents = f.readlines()
myList = []
for line in contents:
line = line.split()
if 'z' not in line:
for j in line:
j = j.split(',')
for l in j:
l = float(l)
myList.append(l)
You can set the document.txt in a string and split it on "z". You get a list where each row is a value from that list. So you can make strings from that list and then split it again on ",". That should do the trick
#open text file in read mode
text_file = open("document.txt", "r")
#read whole file to a string
data = text_file.read()
#close file
text_file.close()
#split the string
data.split("z")
#remove the first empty value of the list
del data[0]
#since you wanted it in 3 separate list
l1 = data[0]
l2 = data[1]
l3 = data[2]
#split the other 3 lists now and done
l1.split(",")
l2.split(",")
l3.split(",")
this gives you the list you wanted.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.