Traditionally, to read a file filled with an array in python, I use the following syntax
x, y, z = loadtxt("myfile.txt", unpack=True)
It works well for single-array files.
Now, I have a more complicated file :
1.5 3.5 2.5 1.6
4
3
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
1 2
3 4
5 6
What I want to do is the following thing :
1.5 3.5 2.5 1.6
-> I want to put them in an array of three variables + 1 scalar
4
-> A = 4, Number of lines of my first array
3
-> B = 3, Number of lines of my second array
My first array with A = 4 lines that I want to load in 5 variables (like the command loadtxt("", unpack = True)
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
My first array with B = 3 lines that I want to load in 2 variables (like the command loadtxt("", unpack = True)
1 2
3 4
5 6
Is there any technique to do this kind of things in python ?
Thank you very much.
You are specifying your own file format, which is not very useful. I would suggest using an existing format such as JSON:
myfile.txt:
{
"a" : [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]
],
"b" : [
...
]
}
read.py
import json
myfile = open("myfile.txt")
myVars = json.load(myfile)
myfile.close()
myVars['a']
you can open a file in python like so:
f = open("myfile.txt")
now you can go through all lines and in each line you can split it by a space:
for line in f.readlines():
linearray = line.split(' ')
arraylength = len(linearray)
print("Array length: "+str(arraylength))
the rest is up to you.
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.