Home > Net >  save output in csv file
save output in csv file

Time:11-24

def execute():
    gtins = read_input_file_mock()
    lst = []

    for gtin in gtins:
        if gtin.get("Message"):
            message = gtin.get("Message")
            message = json.loads(message)
            gtin_string = message.get("gtin")
            lst.append(gtin_string)
    data = json.dumps(list(set(lst)))
    return data

output

["5700302618082", "4063617555079", "4048803188064", "4017182874431", "4006175499096", "0098132561704", "5700302496406", "4056867023092", "5700302496390", "4025087214757", "4056867025102", "4053657584443", "5700302591262", "4056867028493", "4002725988300", "4056867016155", "4060267010620", "5700302591040", "4062741219598", "3614273762816", "7640170574173", "4006175466395", "7617336410668", "4062741219574", "9009656492154", "4062702765522", "4006175490406", "4060596903914", "5700302379822", "4052171102461", "4051432949234", "4974374288165", ]

want to save this result in csv file as a integer!

CodePudding user response:

You can use csvwriter.writerows to write each element of your list in one separate line:

import csv

with open("path_to_the_outputfile.csv", "w", newline="") as f:
    writer=csv.writer(f)
    writer.writerows([[row] for row in data])

# Output (.csv)

5700302618082
4063617555079
4048803188064
4017182874431
4006175499096
...

If you need to add a header (e.g List_of_Numbers), use csvwriter.writerow :

with open("path_to_the_outputfile.csv", "w", newline="") as f:
    writer=csv.writer(f)
    writer.writerow(['List_of_Numbers'])
    writer.writerows([[row] for row in data])
    

CodePudding user response:

import pandas as pd
import numpy as np
pd.DataFrame(np.array(your_data,dtype="int64")).to_csv('your_path.csv')
  • Related