繁体   English   中英

从字符串行读取txt文件中的数据

[英]Reading data from a txt file from string line

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

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

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

Account Number: 3147 Water charge: $5.0

我需要让代码读取文本中的4行。 居民客户每6000加仑支付$ 005每加仑。 商业客户为每8000加仑每加仑$ .006。如果更高,则$ .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)

主要的问题是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环路从来没有终止的原因有二:你永远不读了内环的下一行,像一个人口稠密的字符串'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' 否则,没有break的条件while ,它会永远旋转。

其他一些建议:

1)打开文件时,使用with无需显式openclose文件:

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

2) fh.readline()显式调用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)


暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM