【问题标题】:Reading data from a txt file from string line从字符串行从 txt 文件中读取数据
【发布时间】:2019-03-26 20:34:15
【问题描述】:

我需要编写一个程序来读取存储在 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 business_type == 'b' or 'B' 应该是while business_type == 'b' or business_type == 'B'
  • 除了上面的评论,你为什么还要签入while语句?我觉得您可能会陷入无限循环,因为业务类型始终相同并且在循环内没有更改/

标签: python


【解决方案1】:

两件事。什么都没有出现的原因是您在检查业务类型的 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)

【讨论】:

  • 谢谢。我现在已经开始工作了。我想我离得太远了。
【解决方案2】:

主要问题是您的 while 循环应该只是 if 语句:

        if business_type.lower() == 'b':
            if gallons > 8000:
                water_charge = gallons * .008
            else:
                water_charge = gallons * .006

        elif business_type.lower() == 'r':
            if gallons > 6000:
                water_charge = gallons * .007
            else:
                water_charge = gallons * .005

        else:
            # So you don't get a NameError for no water_charge
            water_charge = 0

你的while 循环永远不会终止的原因有两个:你从来没有读过inside那个内部循环的下一行,像'b' 这样的填充字符串将评估为True:

# Strings with content act like True
if 'b':
    print(True)
# True

# empty strings act as False
if not '':
    print(False)
# False

str.lower() 将小写字符串,因此'R'.lower() 返回'r'。否则while 没有break 条件,它将永远旋转。

其他一些建议:

1) 打开文件时,使用with 消除了显式openclose 文件的需要:

with open('somefile.txt', 'r') as fh:
    # Everything else goes under the with statement

2) 不需要显式调用fh.readline(),因为您可以直接遍历打开的文件:

with open('somefile.txt', 'r') as fh:
    for line in fh:
        # line is the string returned by fh.readline()

这也将在fh 为空或到达文件末尾时终止,当文件为空时您可能无法明确获得'',并且您不再需要while 循环

3) 幻数代码通常是不好的做法(但也很难维护)。例如,如果帐号不正好有 5 个字符怎么办?一个更简洁的方法是使用str.split(' '),它将按空格分割:

with open('somefile.txt', 'r') as fh:
    for line in fh:
        # This will split on spaces returning a list
        # ['3147', 'R', '1000'] which can be unpacked into
        # the three variables like below
        account_number, business_type, gallons = line.split(' ')

        # rest of your code here

总共:


# use with for clean file handling
with open('somefile.txt', 'r') as fh:

    # iterate over the file directly
    for line in fh:
        # split and unpack
        account_number, business_type, gallons = line.split(' ')

        # enforce types
        gallons = float(gallons)

        # .strip() will remove any hanging whitespace, just a precaution
        if business_type.strip().lower() == 'b':
            if gallons > 8000:
                water_charge = gallons * .008
            else:
                water_charge = gallons * .006

        elif business_type.strip().lower() == 'r':
            if gallons > 6000:
                water_charge = gallons * .007
            else:
                water_charge = gallons * .005
        else:
            water_charge = 0.0

        print("Account number:", account_number, "Water charge:$", water_charge)


【讨论】:

  • 感谢您的反馈。我带着下面的答案去了。但我知道你的代码在哪里会更有效,因为输入的数字可能大于 4 位。
猜你喜欢
  • 2013-07-03
  • 2015-05-09
  • 1970-01-01
  • 1970-01-01
  • 2013-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-27
相关资源
最近更新 更多