Tratar un fichero secuencial

¡Hola! soy nuevo por aquí y venía buscando información acerca de tratar ficheros secuenciales con Python.
Tengo un fichero txt de la siguiente forma:

/FILA1 CAMPO1(DATO) CAMPO2(DATO) CAMPO3(DATO)
/FILA2 CAMPO3(DATO) CAMPO4(DATO) CAMPO5(DATO)
/FILA1 CAMPO1(DATO) CAMPO2(DATO) CAMPO3(DATO)
/FILA2…
/…

Como veis los datos de cada campo vienen entre paréntesis (un fichero separado por comas sería mucho más fácil) y cada dos lineas se inicia un nuevo registro.
Lo que quiero es crear una tabla donde tenga CAMPO1, CAMPO2, CAMPO3, etc con sus respectivos datos.
No se si se os ocurre cómo podría hacerlo.

Muchas gracias !!! :slight_smile:

Este codigo toma el file ‘sequential.txt’ con los siguientes valores:

/FILA1 CAMPO1(DATO1) CAMPO2(DATO2) CAMPO3(DATO3)
/FILA2 CAMPO3(DATO4) CAMPO4(DATO5) CAMPO5(DATO6)
/FILA1 CAMPO1(DATO7) CAMPO2(DATO8) CAMPO3(DATO9)
/FILA2 CAMPO3(DATO10) CAMPO4(DATO11) CAMPO5(DATO12)
/FILA1 CAMPO1(DATO13) CAMPO2(DATO14) CAMPO3(DAT15)
/FILA2 CAMPO3(DATO16) CAMPO4(DATO17) CAMPO5(DATO18)

Y crea un csv file ‘result.csv’ con los siquientes valores:

CAMPO1,CAMPO2,CAMPO3,CAMPO4,CAMPO5,CAMPO6
DATO1,DATO2,DATO3,DATO4,DATO5,DATO6
DATO7,DATO8,DATO9,DATO10,DATO11,DATO12
DATO13,DATO14,DAT15,DATO16,DATO17,DATO18
import os
import re
import csv

# change this to your file path ...
ouput_file = './general/result.csv'
input_file = './general/sequential.txt'


def to_csv(values, ouput_file):
    with open(ouput_file, 'a') as f1:
        writer = csv.writer(f1, delimiter=',', lineterminator='\n',)
        writer.writerow(values)


def process(target_string):
    pattern = re.compile('(CAMPO\d+)\((\w+)\)')
    values = []

    for match in pattern.finditer(target_string, re.IGNORECASE):
        _, value = match.groups()
        values.append(value)
    return values


if os.path.exists(ouput_file):
    os.remove(ouput_file)

to_csv(['CAMPO1', 'CAMPO2', 'CAMPO3', 'CAMPO4', 'CAMPO5', 'CAMPO6'], ouput_file)

with open(input_file) as f:
    line = f.readline()
    counter = 0
    records = []
    is_first_line = True

    while line:
        values = process(line)

        new_line = False
        if counter == 2:
            new_line = True
            counter = 0
        counter = counter + 1

        if new_line:
            # start new record ...
            records = []

        records.extend(values)
        if not new_line and not is_first_line:
            to_csv(records, ouput_file)
        line = f.readline()
        is_first_line = False

Espero que te ayude.

Sal2