How to read specific lines of a file into a 2d array in python -
hello chemistry phd student "attempting" write code in python
i have input file below reading in
item: timestep 20000000 item: number of atoms 2 item: box bounds pp pp pp 0 51.577 0 51.048 1.06653 47.9335 item: atoms id type x y z 5 1 15.6042 48.7947 36.9084 27 1 18.4619 1.23863 36.2611 item: timestep 20005000 item: number of atoms 2 item: box bounds pp pp pp 0 51.577 0 51.048 1.03417 47.9658 item: atoms id type x y z 5 1 16.183 47.8777 37.7161 27 1 17.9296 50.8771 36.5807 ...................
i want read file , extract point of array have handled far code
in_name = raw_input('name of input: ') r_file = (open(in_name, 'r')) #readfile j, line in enumerate(r_file): if j%11 == 10:
where getting line starts 27 every time reference.
however can't seem append 1 line multidimensional array.
i want array of floats this
[[27.00], [1.00], [17.9296], [50.8771],[36.5807]]
when read in data not worrying line reading this
lines = [line.split() line in r_file]
which convert using
for x in range(length): y in range(len(lines[x])): lines[x][y]=float(lines[x][y])
how can doing line.split() 1 line @ time , append array desired line?
you should create empty list before start looping on lines of file. then, @ each iteration of loop have data (i guess on last line of every 11-line set?), split line components before (.split()
). makes more sense convert data floats @ point, in opinion. finally, .append()
new line of data list declared @ beginning. gives list of lists of numbers, i.e. 2-dimensional array.
something this:
file_location = # wherever data data = [] open(file_location, 'r') f: index, line in enumerate(f): if index % 11 == 10: data_line = [float(num) num in line.split()] data.append(data_line)
now, data
looks this:
[[27.0, 1.0, 18.4619, 1.23863, 36.2611], [27.0, 1.0, 17.9296, 50.8771, 36.5807]]
additional note: have used with open(...) f:
construction. if you're not familiar it, shorthand saves having .close()
file when you're done it.
Comments
Post a Comment