python如何以可读的形式从csv文件导出数据

2024-05-28 20:36:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个csv文件,其中的字段可以具有可变长度

有没有一种方法可以将其导出为一个文本文件,供人轻松阅读? 例如,行:

01,www.example.com,John,smith,34,interior design
1454,www.anothersite.com/portfolio,Alice,Cooper,76,retired

结果应该是这样的:

01   : www.example.com               : John  : Smith  : 34 : interior design 
1454 : www.anothersite.com/portfolio : Alice : Cooper : 76 : retired

(我使用冒号作为分隔符的示例)


Tags: 文件csv方法comexamplewwwjohndesign
2条回答

在Excel或LibreOffice Calc中打开csv文件将使其可读并为您创建间距。但是,如果要在代码中执行此操作并指定长度, 类似field.ljust(width, ' ')的东西会将任何字段填充到所需的长度

您可以将tabulate模块与csv一起使用

pip install tabulate

以下是方法:

import csv
from tabulate import tabulate

columns = ["Id", "Website", "Name", "Last Name", "Age", "Occupation"]

with open("data.csv") as csv_file:
    reader = csv.reader(csv_file)
    rows = [row for row in reader]
    print(tabulate(rows, tablefmt="pretty", headers=columns))

输出:

+   +               -+   -+     -+  -+        -+
|  Id  |            Website            | Name  | Last Name | Age |   Occupation    |
+   +               -+   -+     -+  -+        -+
|  01  |        www.example.com        | John  |   smith   | 34  | interior design |
| 1454 | www.anothersite.com/portfolio | Alice |  Cooper   | 76  |     retired     |
+   +               -+   -+     -+  -+        -+

相关问题 更多 >

    热门问题