0

I have a text file that has the following structure

"ts": "2021-01-29T00:06:46.929363"
"from": "text"
"to": "text"
"body": "text"

The txt file is quite large.

How can I create a dataframe with the following structure

ts from to body
timestamp text text text
timestamp text text text
timestamp text text text
timestamp text text text
timestamp text text text

Any help is much appreciated!

2
  • can you share about 10 lines ? Commented Feb 28, 2022 at 19:02
  • they all are the same Commented Feb 28, 2022 at 19:04

1 Answer 1

1

Read the file, and use each line to update a dict, when there is 4 keys, save them and start a new dict, finally build the dataframe

import pandas as pd

with open("data.txt") as f:
    batch = {}
    result = []
    for line in f:
        key, value = line.rstrip().split(":", maxsplit=1)
        batch[key.strip('" ')] = value.strip('" ')
        if len(batch) == 4:
            result.append(batch)
            batch = {}

df = pd.DataFrame(result)
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, thank you for your help! This returns a key, value = line.rstrip().split(":", maxsplit=1) ValueError: not enough values to unpack (expected 2, got 1)
@JorgeGomes that means a line has no ":"
Yes, that was the case. Solved. Thank you for your help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.