如何将输出打印在两列并排排列的列中。我已将其设置为打印两列,但我的数据没有排列。哦,顺便说一句,我不允许使用使用列表,元组,集合或词典。特别是你不能使用字符串split()方法,因为它返回一个列表。
my_file=open("project05.data.txt", "r")
outfile = open("dummy.txt","w")
header = my_file.readline()
print("{:^80}".format(header[67:72]),file=outfile)
state = my_file.readline()
print(state[0:17],file=outfile)
count=0
for line in my_file:
count+=1
print(line[0:17],file=outfile)
data="{:^80}".format(line[67:75].rstrip())
print(data,file=outfile)
if count > 10:
break
outfile.close()
Output:
1+MMR
U.S. National
Alabama
89.7+5.8
Alaska
90.5+3.6
Arizona
91.4+3.7
Arkansas
88.3+5.9
California
90.7+5.3
Colorado
86.0+5.5
Connecticut
91.4+5.4
Delaware
94.8+3.4
Dist. of Columbia
96.2+3.1
Florida
93.4+4.0
Georgia
93.9+4.1
答案 0 :(得分:1)
问题是您要两次拨打print
。 print
始终输出到新行。如果您希望两列都在同一行,则只需将两个格式说明符组合成一个字符串:
for line in my_file:
count += 1
output = "{}{:^80}".format(line[0:17], line[67:75].rstrip())
print(output, file=outfile)
if count > 10:
break
当然,您还应该将文件包装在适当的with
语句中:
with open('infile') as my_file, open('outfile', 'w') as outfile:
#above code goes here
# Now don't need to close explisitly