要执行您想要的操作,需要处理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 commas
max_col_widths = [col_width+1 for col_width in max_col_widths]
# read file second time to display its contents with the headers
with open(FILE_NAME) as f:
reader = csv.reader(f, delimiter=',')
# display justified column headers
print(' ' + ' '.join(col_header.ljust(max_col_widths[i])
for i, col_header in enumerate(COL_HEADERS)))
# display column data
for columns in reader:
if "A" in columns and int(columns[5]) < int(columns[3]):
print(columns)
输出:
^{pr2}$
注意:为了便于移植,使用csv模块读取(和写入)csv文件的操作系统应为二进制模式,该模式与Windows类似的“文本”模式有所区别。要在python2中以二进制模式打开一个文件进行读取,请使用open('filename', 'rb'),在python3中使用open('filename', 'r', newline='')。通过将r替换为w来打开文件进行写入。在
还要注意在计算列中每个项的宽度时使用len(repr(col))。这是因为columns是一个列表,print(columns)显示列表中每个项的表示形式,而不是仅显示其值(即对于字符串,这是获取'E5345'和E5345)之间的区别。在