python-3.x 将输出保存在csv文件中

hxzsmxv2  于 2022-11-26  发布在  Python
关注(0)|答案(3)|浏览(208)
def execute():
    d = read_input_file_mock()
    lst = []

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

输出

[“5700302618082”、“4063617555079”、“4048803188064”、“4017182874431”、“4006175499096”、“0098132561704”、“5700302496406”、“4056867023092”]
我想把这个结果保存在csv文件中作为一个整数!

chhkpiq4

chhkpiq41#

您可以使用**csvwriter.writerows**将列表中的每个元素写在单独的一行中:

import csv

with open("path_to_the_outputfile.csv", "w", newline="") as f:
    writer=csv.writer(f)
    writer.writerows([[row] for row in data])
#输出(.csv)
5700302618082
4063617555079
4048803188064
4017182874431
4006175499096
...

如果需要添加标题(例如List_of_Numbers),请使用**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])
5lhxktic

5lhxktic2#

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

dldeef673#

with open("outputfile.json", 'w') as f:
json.dump(execute(), f)

f.关闭()

相关问题