Load and format a CSV file - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Load and format a CSV file (/thread-22076.html) Pages:
1
2
|
RE: Load and format a CSV file - fioranosnake - Oct-30-2019 (Oct-29-2019, 10:09 PM)snippsat Wrote:(Oct-29-2019, 09:29 PM)fioranosnake Wrote: Hi, I there a straight forward way to write the pprint output to a text file?with open('numb.csv') as f,open('out.csv', 'w') as f_out: #next(f) # If need to skip header data = [i.strip() for i in f] data = dict(enumerate(data, 1)) for k,v in data.items(): f_out.write(f'{k}: {v}\n') Hi again, I'm totally grateful for you help. I think I may be trying to do things the hard way..... Essentially, I need to create a JSON file from a text file (eg); 1231241231 1235135135 5457345345 4577865568 8654563848 with the following format : (that I can pass as a payload to an API using requests library) {"1": "1231241231", "2": "1235135135", "3": "5457345345", "4": "4577865568", "5": "8654563848"} I guess I have been trying to confuse things by reading in the values, formatting them, writing them to a text file and then re-reading this in to the API app. No doubt it would be quicker (and easier) to do this in the same script. Im already successfully running the API from a manually formatted 'source' file : #Specify APIKey APIKey = 'KEY' with open("CodestoProcess.txt", "r") as f: Codes =json.load(f) payload = {"Parameters":{"UserAccessKey": APIKey }, "Codes":Codes } headers = {'content-type': 'application/json'} response = requests.post(url, data=json.dumps(payload), headers=headers)Id be so grateful if you could hekp creating a formatted JSON from the source file and make things far more slick. RE: Load and format a CSV file - perfringo - Oct-30-2019 I don't fully understand objective but assuming that you have csv file named 'source-json.csv' with data on rows and want to have json one can simply do something along those lines: import json with open('source-json.csv', 'r') as f: d = {k: v.strip() for (k, v) in enumerate(f, start=1)} j = json.dumps(d)One can write j to file or whatever:
|