Read specific column from .dat-file in Python

Read specific column from .dat-file in Python

with open(results.dat) as f:
    [line.split()[7] for line in f]  

or define a function,

get_col = lambda col: (line.split(t)[col-1] for line in open(results.dat))  

Now call the function with desired column number. get_col(8) gives 8th column data. To store it in array,


You could use csv module.

import csv
with open(file) as f:
    reader = csv.reader(f, delimiter=t)
    for line in reader:

Read specific column from .dat-file in Python

first of all read the file (result.dat) file in a file object

file = open(result.dat)

now create an empty list

lst = []

loop through each line of the file

for line in file:
    lst += [line.split()]

now lst is a list of list , where each inner list is a instance (row ) of the result.dat

now you can extract any column (in your case it is 8th)
apply list comprehension for this

column8 = [x[7] for x in lst]

hope this helps,

Leave a Reply

Your email address will not be published.