python - 从字符串行从 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()
它只是运行而不打印任何东西
解决方案
两件事情。什么都没有出现的原因是您在检查业务类型的 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)
推荐阅读
- windows - 在 Windows 上使用 emscripten 将 Rust 编译为 webassembly 时出错
- python - Python argparse.ArgumentParser - 以数字开头的选项名称?
- java - Jackson - 反序列化嵌套的 JSON 字符串
- python - 为什么多处理会减慢嵌套的 for 循环?
- java - 为什么我在 servlet 的请求参数中得到空值?
- reactjs - 使用 props 和 HOC 测试组件
- r - 如何根据 R 中的多个条件定义新的数据框列?
- testing - 多线程重用空手道功能时出错
- java - 在docker容器中输出Spring Boot日志
- laravel - 在 Laravel Cashier 中创建一次性订阅