首页 > 解决方案 > 如何使用 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)

标签: pythonfiletexttext-files

解决方案


奇怪的是,您将 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))

推荐阅读