要执行您想要的操作,需要处理csv文件的所有行两次,以便确定每列中项目的最大宽度,以便正确对齐列标题。因此,在下面的代码中,文件被读取两次。当然,将整个文件读入内存会更快,如果它不是太大,因为磁盘I/O比访问内存中已有的数据慢得多。在import csv
FILE_NAME = "paintingJobs.txt"
COL_HEADERS = ['title 1', 'title 2', '3', '4', '5', '6']
NUM_COLS = len(COL_HEADERS)
# read file once to determine maximum width of data in columns
with open(FILE_NAME) as f:
reader = csv.reader(f, delimiter=',')
# determine the maximum width of the data in each column
max_col_widths = [len(col_header) for col_header in COL_HEADERS]
for columns in reader:
if "A" in columns and int(columns[5]) < int(columns[3]):
for i, col in enumerate(columns):
max_col_widths[i] = max(max_col_widths[i], len(repr(col)))
# add 1 to each for co