Marco Almeida
Marco Almeida

Reputation: 1303

Split .TXT data as one column into 'n' itens in rows like CSV in Python?

I have a .TXT file with a sequence of data like this:

Name: John Wick
Age: 34
Country: USA
Name: Jeffrey Jones
Age: 55
Country: Africa

And so on, big file. What I want is to put each set of data (Name, Age and Country) into separate rows, like a CSV file, like this:

Name: John Wick,Age: 34,Country: USA
Name: Jeffrey Jones,Age: 55,Country: Africa

I already tried this code, but I no output:

def chunker_list(seq, size):
    return (seq[i::size] for i in range(size))

with open('Data.txt', encoding='utf8') as f:
    print(chunker_list(f, 3))

This is the output:

C:\Users\marco\PycharmProjects\Convert2CSV\venv\Scripts\python.exe 
C:/Users/marco/PycharmProjects/Convert2CSV/main.py
<generator object chunker_list.<locals>.<genexpr> at 0x0000021A73B3BB30>

Process finished with exit code 0

So, any idea on how I could achieve this?

Upvotes: 1

Views: 30

Answers (1)

wjandrea
wjandrea

Reputation: 33179

In a loop, read three lines, remove their trailing newlines, and print them separated by commas.

with open('Data.txt') as f:
    while True:
        try:
            records = [next(f).rstrip('\n') for _ in range(3)]
        except StopIteration:
            break
        print(*records, sep=',')

Output:

Name: John Wick,Age: 34,Country: USA
Name: Jeffrey Jones,Age: 55,Country: Africa

Upvotes: 1

Related Questions