简体   繁体   中英

How to convert the prettytable output to a CSV file using Python

I am trying to convert the table created using the PrettyTable to CSV format using Python in an AWS lambda function. I can able to generate the CSV file but the content inside the CSV file is not in CSV format. Could someone help me to fix if there is any issue in the code?

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

The data content inside the csv file is printing in the same way as in the terminal. Could anyone help me to fix the issue?

You can use the get_csv_string() function instead to get the data correctly formatted for CSV output. This can then be written to an output CSV file:

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())

Giving you test.csv containing:

Col1,Col2,Col3
test1,test2,test3
test4,test5,test6
test7,test8,test9

The get_string() function just returns the data in the same format as would be printed.

The output can be converted to csv by importing csv lib

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)

However this is not recommended since it will distort the format entirely if the output is exported to any format other than the default prettytable format. It is therefore recommended to use Pandas instead in such case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM