How do I read two columns from a .dat file in Python?

1

I have a .dat file with the following numbers:

34875    70.9300    -8.6700

54872    80.0500    16.2500

65456    77.0000    -5.5000

78787    78.2500    22.8300

20890    -8.9200    11.9300

87859    78.2500    15.4700

89556    80.6700    25.0000

I wanted to know what I would do to read only the second and third columns using Python.

    
asked by anonymous 18.08.2017 / 19:21

2 answers

1

You did not specify the final format you should have, but I will assume that it is a list with several sub lists, each of which has the second and third column data.

You can do this as follows:

data = []
with open('tests.dat') as f: # abrir ficheiro em modo leitura ('r'), default, equivalente a ...open('tests.dat', 'r')...
    for line in f:
        if(line.strip() != ''): # exitem linhas vazias, vamos ignora-las
            cols = [i.strip() for i in line.split(' ')[1:]] # vamos quebrar cada linha por espacos e ignorar o primeiro valor de cada linha
            data.append(cols) # adcionar as cols desejadas a nossa lista principal
print(data) # [['70.9300', '-8.6700'], ['80.0500', '16.2500'], ['77.0000', '-5.5000'], ['78.2500', '22.8300'], ['-8.9200', '11.9300'], ['78.2500', '15.4700'], ['80.6700', '25.0000']]

More didactic way:

data = []
with open('tests.dat') as f:
    for line in f:
        if(line.strip() != ''): # exitem linhas vazias, vamos ignora-las, nao fazer nada com elas
            line_spl = line.split(' ') # vamos quebrar cada linha por espacos
            cols = line_spl[1:] # aproveitar o segundo e terceiro elemento da linha quebrada por espacos
            data.append([cols[0], cols[1].strip()]) # retirar '\n' do terceiro elemento, segundo em cols
print(data) # [['70.9300', '-8.6700'], ['80.0500', '16.2500'], ['77.0000', '-5.5000'], ['78.2500', '22.8300'], ['-8.9200', '11.9300'], ['78.2500', '15.4700'], ['80.6700', '25.0000']]

You can print every cycle, line,% desired%:

with open('tests.dat') as f:
    for line in f:
        if(line.strip() != ''):
            line_spl = line.split(' ')
            cols = [i.strip() for i in line.split(' ')[1:]]
            print(cols[0], cols[1].strip())
    
18.08.2017 / 19:27
0

Short solution:

with open('arq.txt') as arq:
    dados = [line.split('    ')[1:] for line in arq.readlines() if line.strip()]
print(dados)
    
22.08.2017 / 03:28