首页 > 解决方案 > 从字符串行从 txt 文件中读取数据

问题描述

我需要编写一个程序来读取存储在 txt 文件中的数据。前任:

3147 R 1000
2168 R 6002
5984 B 2000
7086 B 8002

第一个数字是“帐号”,“R”是住宅分类,最后一个数字是“使用的加仑数”。我需要制作一个程序来打印这个:

Account Number: 3147 Water charge: $5.0

我需要让代码在文本中读取 4 行。住宅客户为前 6000 美元支付每加仑 0.005 美元。如果更高,则为 0.007 美元。商业客户为前 8000 美元支付每加仑 0.006 美元。如果更高,则为 0.008 美元,我需要显示每 4 行的产品。下面的代码是我尝试过的。我可能会走得很远。

我试过下面的代码:

def main():
    input_file = open('C:\Python Projects\Project 
1\water.txt', 'r')
    empty_str = ''
    line = input_file.readline()

    while line != empty_str:

        account_number = int(line[0:4])
        gallons = float(line[7:11])
        business_type = line[5]
        while business_type == 'b' or 'B':
            if gallons > 8000:
                water_charge = gallons * .008
            else:
                water_charge = gallons * .006
        while business_type == 'r' or 'R':
            if gallons > 6000:
                water_charge = gallons * .007
            else:
                water_charge = gallons * .005

        print("Account number:", account_number, "Water 
 charge:$", water_charge)
        line = input_file.readline()

    input_file.close()
main()

它只是运行而不打印任何东西

标签: python

解决方案


两件事情。什么都没有出现的原因是您在检查业务类型的 while 循环中陷入了无限循环。将其更改为 if 语句可以修复它。

此外,当您使用 and、or 或其他一些运算符时,您必须再次指定要比较的变量。

读取文件行的​​ while 语句应如下所示:

while line != empty_str:

    account_number = int(line[0:4])
    gallons = float(line[7:11])
    business_type = line[5]
    if business_type == 'b' or business_type =='B':
        if gallons > 8000:
            water_charge = gallons * .008
        else:
            water_charge = gallons * .006
    if business_type == 'r' or business_type =='R':
        if gallons > 6000:
            water_charge = gallons * .007
        else:
            water_charge = gallons * .005

    print("Account number:", account_number, "Water charge:$", water_charge)
    line = input_file.readline()

输出:

('Account number:', 3147, 'Water charge:$', 5.0)

推荐阅读