python - 如何使用 python 在文本文件中添加新列?
问题描述
这是初始文本文件:
Name Height(m) Weight(kg)
Joe 1.82 72.57
Mary 1.60 63.50
Dion 1.90 90.71
Kayla 1.72 66.31
Jose 1.78 70.23
Sofia 1.63 65.12
Erik 1.98 92.21
Sara 1.57 65.77
我正在尝试添加另一列(BMI)。我可以在 python 中进行计算。我已经以 'r+' 形式打开了代码。我的代码如下:
open_file = open('data.txt', 'r+')
def clean_word(word):
return word.strip().lower()
#clean_word(open_file)
line = open_file.readlines() # READS ALL LINES, EACH LINE INDIVIDUALLY
line.pop(0) # DELETES FIRST LINE
bmi_list = []
height_list = []
weight_list = []
new_file = open('data2.txt', 'w')
#file = open('data.txt', 'w+')
for word in line:
word = clean_word(word)
word_list = word.split()
height = float(word_list[1])
weight = float(word_list[2])
bmi = '{:.2f}'.format(weight/height**2)
bmi_list.append(bmi)
word_list.insert(3, bmi) # 'INSERTS BMI VALUES TO NORMAL LIST
#print(word_list)
height_list.append(height)
weight_list.append(weight)
解决方案
奇怪的是,您将 bmi 存储为字符串,将重量和高度存储为浮点数。你可能想要这样的东西:
for word in line:
word = clean_word(word)
word_list = word.split()
height = float(word_list[1])
weight = float(word_list[2])
bmi = weight/height**2
bmi_list.append(bmi)
height_list.append(height)
weight_list.append(weight)
print('{:.2f} {:.2f} {:.2f}'.format(height,weight,bmi))
推荐阅读
- signalr-hub - 从域服务和应用层访问 SignalR
- tslint - 用于对象函数调用的 tslint ter-indent
- python-3.x - 如何将每行列值与后续行列值相加并使用新旧行创建新数据框
- javascript - 简化表格分页ajax php mysql
- python-3.x - python web scraping:如何读取 Twitter 类名或 IDS 或 DIV.name ......或任何标识符
- javascript - 根据课程的可用性添加和删除课程
- c++ - 如何将二维数组初始为0
- android - Flutter Checking 以编程方式启用 USB 调试
- git - 如果提交包含超过 200kb 的文件,则其中一个用户无法推送到 gitlab
- wordpress - 需要在 Woocommerce 中将多个特定产品的电子邮件通知发送到包含订单号的不同电子邮件