0

I'm creating a list of values, which get exported as a text file. I'm then later re-importing the same text file. The issue is I'm trying to utilise json when handling the string values to make it easier to read the data.

I'm currently getting a lot of spaces when reading the text file though.

import pandas as pd
import datetime
import json


date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

item = 'bike'

price = '10'

new_item = [date, item, price]


data = []

data.append(new_item)

jsondata = json.dumps(data)


with open("file.txt", 'w') as output:
        for row in jsondata:               
            output.write(str(row) + '\n')

#re-import txt file
df = pd.read_json("file.txt")
df.columns = ["Datetime", "Item", "Cost"]

Out:

                                            Datetime                      Item            Cost
0  \r\n2\r\n0\r\n2\r\n4\r\n-\r\n0\r\n2\r\n-\r\n0\...  \r\nb\r\ni\r\nk\r\ne\r\n  \r\n1\r\n0\r\n

Intended:

                Datetime  Item Cost
0    2020-02-06 17:31:15  bike   10               
2
  • I don't know what you're trying to do with for row in jsondata:. You do understand jsondata is a string right? Iterating over a string gives you individual characters of it. So you're just printing one character per line. It's weird pd.read_json didn't just throw an error on reading that file. Commented Feb 6, 2024 at 6:39
  • In your own words, whre the code says for row in jsondata:, what do you think this should mean? What do you expect jsondata to look like at this point in the code? (Did you try to check? Was it like you expected)? Commented Feb 6, 2024 at 6:47

1 Answer 1

1

jsondata is a string generated by json.dumps(). So if you do for row in jsondata: you iterate over the string, character by character.

You can simply use json.dump(data, output) to write data to the file output in the form of a JSON object.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.