1

I am trying to convert the table created using the PrettyTable to CSV format using Python in an AWS lambda function. I am able to generate the CSV file, but the content inside the CSV file is not in CSV format. How can I 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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
karthik
  • 417
  • 1
  • 7
  • 15
  • That is a very roundabout way to create a `.csv` file from your data. Use the `csv` module to create a `csv.reader` object and call `myreader.add_row()` for each row you want in the file. – BoarGules Jun 07 '22 at 15:00

3 Answers3

4

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.

Martin Evans
  • 45,791
  • 17
  • 81
  • 97
1

The output can be converted to CSV by importing the csv library:

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 a case.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Milan
  • 71
  • 5
1

Update 2023: use get_string() instead as get_csv_string() no longer available

with open('test.csv', 'w', newline='') as f_output:
    f_output.write(x.get_string())
MMSA
  • 810
  • 8
  • 22