如何在Python中漂亮地打印CSV文件

psxls

如何使用Python(而不是任何外部工具)漂亮地打印CSV文件?

例如,我有这个CSV文件:

title1|title2|title3|title4
datalongdata|datalongdata|data|data

data|data|data|datalongdatadatalongdatadatalongdatadatalongdatadatalongdata
data|data'data|dat

我想将其转换为可视化的表格。例如,类似这样的内容:

+ --------------------------------------------------------------------------------------------------- +
| title1       | title2       | title3 | title4                                                       |
+ --------------------------------------------------------------------------------------------------- +
| datalongdata | datalongdata | data   | data                                                         |
|              |              |        |                                                              |
| data         | data         | data   | datalongdatadatalongdatadatalongdatadatalongdatadatalongdata |
| data         | data'data    | dat    |                                                              |
+ --------------------------------------------------------------------------------------------------- +
psxls

用法:

pretty.pretty_file(filename,*** options *)

读取CSV文件并将数据作为表格直观地打印到新文件中。filename,是给定的CSV文件。可选的*** options *关键字参数是Python标准库csv模块的方言和格式设置参数以及以下列表的并集:

  • new_delimiter:新的列分隔符(默认为“ |”)
  • border:如果要打印表格的边框,则为布尔值(默认为True)
  • border_vertical_left:表格的左边框(默认为“ |”)
  • border_vertical_right:表格的右边框(默认为“ |”)
  • border_horizo​​ntal:表格的顶部和底部边框(默认为“-”)
  • border_corner_tl:表格的左上角(默认为“ +”)
  • border_corner_tr:表格的右上角(默认为“ +”)
  • border_corner_bl:表格的左下角(默认border_corner_tl相同
  • border_corner_br:表格的右下角(默认border_corner_tr相同
  • header:布尔值,如果第一行是表头(默认为True)
  • border_header_separator:标题和表格之间的边界(默认border_horizo​​ntal相同
  • border_header_left:表标题的左边框(默认border_corner_tl相同
  • border_header_right:表标题的右边框(默认border_corner_tr相同
  • new_filename:新文件的文件名(默认为“ new_” + filename
  • newline:定义如何分隔表的行(默认为“ \ n”)

例:

import pretty_csv
pretty_csv.pretty_file("test.csv", header=False, border=False, delimiter="|")

Python 3:

这是一个Python 2实现。对于Python 3,您必须将两次出现的行更改为open(filename, "rb") as input:open(filename, "r", newline="") as input:因为csv.reader在Python 3中希望以文本模式打开文件。

模块:

import csv
import os

def pretty_file(filename, **options):
    """
    @summary:
        Reads a CSV file and prints visually the data as table to a new file.
    @param filename:
        is the path to the given CSV file.
    @param **options:
        the union of Python's Standard Library csv module Dialects and Formatting Parameters and the following list:
    @param new_delimiter:
        the new column separator (default " | ")
    @param border:
        boolean value if you want to print the border of the table (default True)
    @param border_vertical_left:
        the left border of the table (default "| ")
    @param border_vertical_right:
        the right border of the table (default " |")
    @param border_horizontal:
        the top and bottom border of the table (default "-")
    @param border_corner_tl:
        the top-left corner of the table (default "+ ")
    @param border_corner_tr:
        the top-right corner of the table (default " +")
    @param border_corner_bl:
        the bottom-left corner of the table (default same as border_corner_tl)
    @param border_corner_br:
        the bottom-right corner of the table (default same as border_corner_tr)
    @param header:
        boolean value if the first row is a table header (default True)
    @param border_header_separator:
        the border between the header and the table (default same as border_horizontal)
    @param border_header_left:
        the left border of the table header (default same as border_corner_tl)
    @param border_header_right:
        the right border of the table header (default same as border_corner_tr)
    @param newline:
        defines how the rows of the table will be separated (default "\n")
    @param new_filename:
        the new file's filename (*default* "/new_" + filename)
    """

    #function specific options
    new_delimiter           = options.pop("new_delimiter", " | ")
    border                  = options.pop("border", True)
    border_vertical_left    = options.pop("border_vertical_left", "| ")
    border_vertical_right   = options.pop("border_vertical_right", " |")
    border_horizontal       = options.pop("border_horizontal", "-")
    border_corner_tl        = options.pop("border_corner_tl", "+ ")
    border_corner_tr        = options.pop("border_corner_tr", " +")
    border_corner_bl        = options.pop("border_corner_bl", border_corner_tl)
    border_corner_br        = options.pop("border_corner_br", border_corner_tr)
    header                  = options.pop("header", True)
    border_header_separator = options.pop("border_header_separator", border_horizontal)
    border_header_left      = options.pop("border_header_left", border_corner_tl)
    border_header_right     = options.pop("border_header_right", border_corner_tr)
    newline                 = options.pop("newline", "\n")

    file_path = filename.split(os.sep)
    old_filename = file_path[-1]
    new_filename            = options.pop("new_filename", "new_" + old_filename)

    column_max_width = {} #key:column number, the max width of each column
    num_rows = 0 #the number of rows

    with open(filename, "rb") as input: #parse the file and determine the width of each column
        reader=csv.reader(input, **options)
        for row in reader:
            num_rows += 1
            for col_number, column in enumerate(row):
                width = len(column)
                try:
                    if width > column_max_width[col_number]:
                        column_max_width[col_number] = width
                except KeyError:
                    column_max_width[col_number] = width

    max_columns = max(column_max_width.keys()) + 1 #the max number of columns (having rows with different number of columns is no problem)

    if max_columns > 1:
        total_length = sum(column_max_width.values()) + len(new_delimiter) * (max_columns - 1)
        left = border_vertical_left if border is True else ""
        right = border_vertical_right if border is True else ""
        left_header = border_header_left if border is True else ""
        right_header = border_header_right if border is True else ""

        with open(filename, "rb") as input:
            reader=csv.reader(input, **options)
            with open(new_filename, "w") as output:
                for row_number, row in enumerate(reader):
                    max_index = len(row) - 1
                    for index in range(max_columns):
                        if index > max_index:
                            row.append(' ' * column_max_width[index]) #append empty columns
                        else:
                            diff = column_max_width[index] - len(row[index])
                            row[index] = row[index] + ' ' * diff #append spaces to fit the max width

                    if row_number==0 and border is True: #draw top border
                        output.write(border_corner_tl + border_horizontal * total_length + border_corner_tr + newline)
                    output.write(left + new_delimiter.join(row) + right + newline) #print the new row
                    if row_number==0 and header is True: #draw header's separator
                        output.write(left_header + border_header_separator * total_length + right_header + newline)
                    if row_number==num_rows-1 and border is True: #draw bottom border
                        output.write(border_corner_bl + border_horizontal * total_length + border_corner_br)

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何在Python中漂亮地打印CSV文件

来自分类Dev

如何在Delphi中漂亮地打印JSON?

来自分类Dev

如何“漂亮地打印” python熊猫DatetimeIndex

来自分类Dev

如何使用lxml和python漂亮地打印xml文件的子树?

来自分类Dev

如何在C / C ++中更漂亮地打印调用堆栈?

来自分类Dev

如何漂亮地打印变量

来自分类Dev

如何在Julia中将矩阵漂亮地打印为String?

来自分类Dev

在python中,如何获取自己的异常类以在shell中漂亮地打印出来?

来自分类Dev

用knitr从单独的文件中漂亮地打印SQL代码

来自分类Dev

如何从ios中的原始内容漂亮地打印响应请求

来自分类Dev

我如何漂亮地在ansible中打印对象?

来自分类Dev

在Python中漂亮地打印字典矩阵

来自分类常见问题

如何使用Go漂亮地打印JSON?

来自分类Dev

如何在Jersey Trace中打印漂亮的JSON?

来自分类Dev

如何从命令行漂亮地打印具有长列的csv?

来自分类Dev

如何从SQuirreL结果漂亮地打印CSV /电子表格?

来自分类Dev

如何在同一行中用长数组漂亮地打印json

来自分类Dev

如何使用Scala在spark中漂亮地打印JSON数据框?

来自分类Dev

如何使用Scala在spark中漂亮地打印JSON数据框?

来自分类Dev

在Python中漂亮地打印JSON.dump 2d数组

来自分类Dev

如何在Python中编写.csv文件?

来自分类Dev

如何在python中枚举.csv文件?

来自分类Dev

如何在Python中删除CSV文件

来自分类Dev

如何在python中解析csv文件

来自分类Dev

如何在Python的CSV文件中的组中打印出现的唯一名称

来自分类Dev

如何在python中更好地读取文件行

来自分类Dev

使用Rook时如何使JSON响应漂亮地打印?

来自分类Dev

如何用方括号漂亮地打印JSON?

来自分类Dev

朱莉娅:如何漂亮地打印数组?

Related 相关文章

  1. 1

    如何在Python中漂亮地打印CSV文件

  2. 2

    如何在Delphi中漂亮地打印JSON?

  3. 3

    如何“漂亮地打印” python熊猫DatetimeIndex

  4. 4

    如何使用lxml和python漂亮地打印xml文件的子树?

  5. 5

    如何在C / C ++中更漂亮地打印调用堆栈?

  6. 6

    如何漂亮地打印变量

  7. 7

    如何在Julia中将矩阵漂亮地打印为String?

  8. 8

    在python中,如何获取自己的异常类以在shell中漂亮地打印出来?

  9. 9

    用knitr从单独的文件中漂亮地打印SQL代码

  10. 10

    如何从ios中的原始内容漂亮地打印响应请求

  11. 11

    我如何漂亮地在ansible中打印对象?

  12. 12

    在Python中漂亮地打印字典矩阵

  13. 13

    如何使用Go漂亮地打印JSON?

  14. 14

    如何在Jersey Trace中打印漂亮的JSON?

  15. 15

    如何从命令行漂亮地打印具有长列的csv?

  16. 16

    如何从SQuirreL结果漂亮地打印CSV /电子表格?

  17. 17

    如何在同一行中用长数组漂亮地打印json

  18. 18

    如何使用Scala在spark中漂亮地打印JSON数据框?

  19. 19

    如何使用Scala在spark中漂亮地打印JSON数据框?

  20. 20

    在Python中漂亮地打印JSON.dump 2d数组

  21. 21

    如何在Python中编写.csv文件?

  22. 22

    如何在python中枚举.csv文件?

  23. 23

    如何在Python中删除CSV文件

  24. 24

    如何在python中解析csv文件

  25. 25

    如何在Python的CSV文件中的组中打印出现的唯一名称

  26. 26

    如何在python中更好地读取文件行

  27. 27

    使用Rook时如何使JSON响应漂亮地打印?

  28. 28

    如何用方括号漂亮地打印JSON?

  29. 29

    朱莉娅:如何漂亮地打印数组?

热门标签

归档