python怎么添加标题_如何将标题添加到列表(csv)
要执⾏您想要的操作,需要处理csv⽂件的所有⾏两次,以便确定每列中项⽬的最⼤宽度,以便正确对齐列标题。因此,在下⾯的代码中,⽂件被读取两次。当然,将整个⽂件读⼊内存会更快,如果它不是太⼤,因为磁盘I/O⽐访问内存中已有的数据慢得多。在import csv
FILE_NAME = ""
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 = ader(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 = ader(f, delimiter=',')
# display justified column headers
print(' ' + ' '.join(col_header.ljust(max_col_widths[i])
python怎么读csv数据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)之间的区别。在

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。