Home > other >  Is there any way I can code to read txt file of atomic coordinates to represent each colum as a list
Is there any way I can code to read txt file of atomic coordinates to represent each colum as a list

Time:06-08

This is the atomic coordinates

XYZ
A 5.98974561 7.80124465 15.1032457
B 5.60245671 7.50214457 16.0012454

I started coding as

with open(filename) as f:
    while True:
        line = f.readlines()
        if not line:
           break
        print((line[1]))
        print((line[2]))

And the results came as:

A 5.98974561 7.80124465 15.1032457
B 5.60245671 7.50214457 16.0012454

But I wanted it to be

A = [5.98974561 7.80124465 15.1032457]
B = [5.60245671 7.50214457 16.0012454]
 

CodePudding user response:

You could do it like this with Abuday's suggestion:

    with open(filename) as f:
        lines = f.readlines()[1:]
    
    dictionary = {}    
    for i in lines:
        dictionary[i.split()[0]] = i.split()[1:]

This will give you a dictionary with indices (A, B, ...) as keys and lists as values.

CodePudding user response:

Something like this could suite you

with open(filename) as f:
    line = f.readline() # to skip first line
    col_0 = [] # so store the first column
    col_1 = [] # so store the second column
    col_2 = [] # so store the third column
    col_3 = [] # so store the fourth column
    while True:
        line = f.readline() # read line one  by one
        if not line:
           break
        line = line.replace('\n','') # replace line return with nothing
        splitline = line.split(' ')
        col_0.append(splitline[0]) # append value of the first column   convert to float
        col_1.append(float(splitline[1])) # append value of the second column   convert to float
        col_2.append(float(splitline[2])) # append value of the third column    convert to float
        col_3.append(float(splitline[3])) # append value of the fourth column   convert to float
        print(splitline[0]   ' = '   str(splitline[1])   ' '   str(splitline[2])   ' '   str(splitline[3])   )
print(col_0)
print(col_1)
print(col_2)
print(col_3)

But I think there is more efficient ways to read 3D coordinate files. For example using numpy:

import numpy as np
filename = 't.txt'
Name = np.loadtxt(filename, skiprows=1, usecols=0,dtype = 'S1' )
Coordianates = np.loadtxt(filename, skiprows=1, usecols=(1,2,3) )
print( Name,Coordianates)

CodePudding user response:

In order to produce the exact output as shown in the question then:

FILENAME = 'foo.txt'
with open(FILENAME) as data:
    for line in data.readlines()[1:]:
        t = line.split()
        print(f'{t[0]} = [{" ".join(t[1:])}]')

Output:

A = [5.98974561 7.80124465 15.1032457]
B = [5.60245671 7.50214457 16.0012454]
  • Related