1、python用prettytable输出漂亮的表格
https://linuxops.org/blog/python/prettytable.html
2、写文件
f = open('C:\Users\hfqn\Desktop\test.txt', 'w') f.write('Hello, world!') f.close()
3、打印表格文本,自动对齐:
demo:
def format_table(columns_name, data): max_len = 0 for col in columns_name: if max_len < len(col): max_len = len(col) for d in data[0]: if max_len < len(str(d)): max_len = len(str(d)) line_str = "+--------{}--------".format("-"*(2*max_len)) first_line = line_str * len(columns_name) + "+" column_line = '' lens = len(line_str) for col in columns_name: blank = ' ' * (int((lens - len(col) * 2) / 2)) column_line = "{}|{}{}{}".format(column_line, blank, col, blank) data_lines = None for i, data_line in enumerate(data): n1 = (int((lens - len(str(i))) / 2)) n2 = n1 if n1*2+len(str(i))+1 > lens: n2 = n1 - 1 if n1 * 2 + len(str(i))+1 < lens: n2 = n1 + 1 line = "|{}{}{}".format(' '*n1, i, ' '*n2) n1 = (int((lens - len(str(data_line))) / 2)) n2 = n1 if n1 * 2 + len(str(data_line))+1 > lens: n2 = n1 - 1 if n1 * 2 + len(str(data_line))+1 < lens: n2 = n1 + 1 line = "{}|{}{}{}".format(line, ' '*n1, data_line, ' '*n2) if data_lines: data_lines = "{} {}{}".format(data_lines, line, '|') else: data_lines = "{}{}".format(line, '|') result = "{} {}| {} {} {}".format(first_line, column_line, first_line, data_lines, first_line) return result