我将这5个变量分配给5个不同列的和:
TotalUnitsSold = mmSalesDF['Units Sold'].sum()
TotalUnitsCost = mmSalesDF['Unit Cost'].sum()
TotalRevenue = mmSalesDF['Total Revenue'].sum()
TotalCost = mmSalesDF['Total Cost'].sum()
TotalProfit = mmSalesDF['Total Profit'].sum()
我需要使用append将其写入一个新的txt文件,所以我创建了一个包含字符串和变量的列表[]:
sumsList = ['Sums:',
'Units sold:',TotalUnitsSold,
'Unit cost:',TotalUnitsCost,
'Total revenue:',TotalRevenue,
'Total cost:',TotalCost,
'Total profit:',TotalProfit]
with open('DataSample/MM_Calc.txt', "a+") as writer:
for line in sumsList:
writer.write(f'{line}n')
输出如下:输出
但是要求的格式应该是这样的:要求格式的
所以我想知道有什么方法可以做到这一点?
TotalUnitsSold = 5
TotalUnitsCost = 600
TotalRevenue = 60
TotalCost = 5000
TotalProfit = 100
sumsList = ['Sums:',
'Units sold: ' + str(TotalUnitsSold),
'Unit cost: ' + str(TotalUnitsCost),
'Total revenue: ' + str(TotalRevenue),
'Total cost: ' + str(TotalCost),
'Total profit: ' + str(TotalProfit)]
with open('MM_Calc.txt', "w+") as writer:
for line in sumsList:
writer.write(f'{line}n')
#output:
Sums:
Units sold: 5
Unit cost: 600
Total revenue: 60
Total cost: 5000
Total profit: 100
按以下方式设置列表格式:
sumsList = ['Sums:',
'Units sold: ({})'.format(TotalUnitsSold),
'Unit cost: ({})'.format(TotalUnitsCost),
'Total revenue: ({})'.format(TotalRevenue),
'Total cost: ({})'.format(TotalCost),
'Total profit: ({})'.format(TotalProfit)]
sumsList = ['Sums:',
'Units sold:',TotalUnitsSold,
'Unit cost:',TotalUnitsCost,
'Total revenue:',TotalRevenue,
'Total cost:',TotalCost,
'Total profit:',TotalProfit]
你把它们都列为项,而不是行。
for line in sumsList:
当你像这样循环时,它将在每个换行符之后打印一个换行符。
如果您想只使用list,并在同一行中打印key-value,请尝试这样做。
sumsList = ['Sums:',
'Units sold: ' + str(TotalUnitsSold),
'Unit cost: ' + str(TotalUnitsCost),
'Total revenue: ' + str(TotalRevenue),
'Total cost: ' + str(TotalCost),
'Total profit: ' + str(TotalProfit)]