[英]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.我正在尝试使用 AWS lambda function 中的 Python 将使用 PrettyTable 创建的表转换为 CSV 格式。我可以生成 CSV 文件,但 CSV 文件中的内容不在 180105388 格式中。 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. csv 文件中的数据内容打印方式与终端相同。 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.您可以改用
get_csv_string()
函数来获取为 CSV 输出正确格式化的数据。 This can then be written to an output CSV file:然后可以将其写入输出 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())
Giving you test.csv
containing:给你
test.csv
包含:
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. get_string()
函数只返回与打印格式相同的数据。
The output can be converted to csv by importing csv lib通过导入 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)
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.但是,不建议这样做,因为如果将 output 导出为默认漂亮格式以外的任何格式,它会完全扭曲格式。 It is therefore recommended to use Pandas instead in such case
因此,建议在这种情况下使用 Pandas
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.