Will C
Will C

Reputation: 129

Reading in specific data from a text file

I am trying to read in specific data from the text file 10-10-1CNT_pot.pot_fmt. The data needed is a,b and c as well as the fft coefficients (25,300,300) in this case. Currently the only way I can think of to read these in, is from their position in the text file. I do not like this however as it is prone to bugs if the text file changes slightly. Can anyone suggest an alternate method?

Please see an example text file below (and the buggy code):

BEGIN header

       Real Lattice(A)               Lattice parameters(A)    Cell Angles
   2.4675850   0.0000000   0.0000000     a =    2.467585  alpha =   90.000000
   0.0000000  30.0000000   0.0000000     b =   30.000000  beta  =   90.000000
   0.0000000   0.0000000  30.0000000     c =   30.000000  gamma =   90.000000

 1                            ! nspins
25   300   300                ! fine FFT grid along <a,b,c>
END header: data is "<a b c> pot" in units of Hartrees

Code:

file = open("10-10-1CNT_pot.pot_fmt", 'r')
lines = file.readlines()
file.close()


parts = lines[3].split() 
a = parts[5]

parts1 = lines[4].split() 
b = parts1[5]

parts2 = lines[5].split()
c = parts2[5]

parts3 = lines[8].split()
width = parts3[0]

parts4 = lines[8].split()
height = parts4[1]

parts5 = lines[8].split()
depth = parts5[2]

Upvotes: 0

Views: 58

Answers (1)

keyvan vafaee
keyvan vafaee

Reputation: 466

you need to use regex so :

import re


s=""

with open('your_file_name','r') as myfile: 
 a = myfile.readlines()

for i in a:
 s +=i

list1=list()

list2=list()



list1.append(re.findall('(a = .* ) alpha | (b = .* ) beta | (c = .* ) gamma', s ,re.M))



list2.append(re.findall('(.*) !',s))
for i in list2:

 print i[1]

for i in list1 :
 for j in i:
  print j[0],j[1],j[2]

output:

25   300   300    

a =    2.467585   
 b =   30.000000  
  c =   30.000000 

Upvotes: 2

Related Questions