![](/img/trans.png)
[英]How to convert JSON to CSV file from s3 and save it in same s3 bucket using Glue job
[英]How to convert the prettytable output to a CSV file using Python
我正在嘗試使用 AWS lambda function 中的 Python 將使用 PrettyTable 創建的表轉換為 CSV 格式。我可以生成 CSV 文件,但 CSV 文件中的內容不在 180105388 格式中。 如果代碼中有任何問題,有人可以幫我解決嗎?
import os
import json
from prettytable import PrettyTable
data = PrettyTable(["Col1","Col2","Col3"])
data.add_row(["test1","test2","test3"])
data.add_row(["test4","test5","test6"])
data.add_row(["test7","test8","test9"])
print(data)
data_string = data.get_string()
with open('/tmp/test.csv',w) as f:
f.write(data_string)
f.close
csv 文件中的數據內容打印方式與終端相同。 誰能幫我解決這個問題?
您可以改用get_csv_string()
函數來獲取為 CSV 輸出正確格式化的數據。 然后可以將其寫入輸出 CSV 文件:
from prettytable import PrettyTable
data = PrettyTable(["Col1","Col2","Col3"])
data.add_row(["test1","test2","test3"])
data.add_row(["test4","test5","test6"])
data.add_row(["test7","test8","test9"])
print(data)
with open('test.csv', 'w', newline='') as f_output:
f_output.write(data.get_csv_string())
給你test.csv
包含:
Col1,Col2,Col3
test1,test2,test3
test4,test5,test6
test7,test8,test9
get_string()
函數只返回與打印格式相同的數據。
通過導入 csv lib 可以將 output 轉換為 csv
import os
import json
import csv
from prettytable import PrettyTable
data = PrettyTable(["Col1","Col2","Col3"])
data.add_row(["test1","test2","test3"])
data.add_row(["test4","test5","test6"])
data.add_row(["test7","test8","test9"])
print(data)
data_string = data.get_string()
with open('test.csv', 'w', newline = '') as f:
writer = csv.writer(f)
writer.writerows(data)
但是,不建議這樣做,因為如果將 output 導出為默認漂亮格式以外的任何格式,它會完全扭曲格式。 因此,建議在這種情況下使用 Pandas
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.