Creating a Table

3.3. Creating a Table#

Ref: https://scipython.com/book/chapter-2-the-core-python-language-i/string-representation-of-integers-with-comma-separated-thousands/

title = '|' + '{:^51}'.format('Cereal Yields (kg/ha)') + '|'
line = '+' + '-'*15 + '+' + ('-'*8 + '+')*4
row = '| {:<13} |' + ' {:6,d} |'*4
header = '| {:^13s} |'.format('Country') + (' {:^6d} |'*4).format(1980, 1990,
                                                                  2000, 2010)
print('+' + '-'*(len(title)-2) + '+',
      title,
      line,
      header,
      line,
      row.format('China', 2937, 4321, 4752, 5527),
      row.format('Germany', 4225, 5411, 6453, 6718),
      row.format('United States', 3772, 4755, 5854, 6988),
      line,
      sep='\n')
+---------------------------------------------------+
|               Cereal Yields (kg/ha)               |
+---------------+--------+--------+--------+--------+
|    Country    |  1980  |  1990  |  2000  |  2010  |
+---------------+--------+--------+--------+--------+
| China         |  2,937 |  4,321 |  4,752 |  5,527 |
| Germany       |  4,225 |  5,411 |  6,453 |  6,718 |
| United States |  3,772 |  4,755 |  5,854 |  6,988 |
+---------------+--------+--------+--------+--------+

3.3.1. Writing to a file#

Use with context to manage closing file automatically.

with open('test_file.txt', 'w') as file:
    file.write('line1\nline2')
title = '|' + '{:^51}'.format('Cereal Yields (kg/ha)') + '|'
line = '+' + '-'*15 + '+' + ('-'*8 + '+')*4
row = '| {:<13} |' + ' {:6,d} |'*4
header = '| {:^13s} |'.format('Country') + (' {:^6d} |'*4).format(1980, 1990,
                                                                  2000, 2010)
file_content = '\n'.join(('+' + '-'*(len(title)-2) + '+',
      title,
      line,
      header,
      line,
      row.format('China', 2937, 4321, 4752, 5527),
      row.format('Germany', 4225, 5411, 6453, 6718),
      row.format('United States', 3772, 4755, 5854, 6988),
      line))

with open('test_file2.txt', 'w') as file:
    file.write(file_content)