简体   繁体   English

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

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

I need to write a program to read data stored in a txt file. 我需要编写一个程序来读取存储在txt文件中的数据。 EX: 例如:

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

The first number is an "account number" the "R" is a residential classification, and the last number is "gallons used". 第一个数字是“帐号”,“ R”是住宅分类,最后一个数字是“使用的加仑”。 I need to produce a program to print this: 我需要产生一个程序来打印此:

Account Number: 3147 Water charge: $5.0

I need to have the code read 4 lines in the text. 我需要让代码读取文本中的4行。 Residential customers pay $.005 per gallon for first 6000. If higher $.007. 居民客户每6000加仑支付$ 005每加仑。 Business customers pay $.006 per gallon for first 8000. If higher, $.008 I need to display the product of each 4 lines. 商业客户为每8000加仑每加仑$ .006。如果更高,则$ .008我需要显示每4行的乘积。 The code below is what I tried. 下面的代码是我尝试的。 I may be way off. 我可能离我远去。

I've tried the code below: 我试过下面的代码:

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()

It just runs without printing anything 它只是运行而无需打印任何内容

Two things. 两件事情。 The reason nothing is appearing is because you are stuck in an infinite loop in the while loop that checks the business type. 什么都不出现的原因是因为您陷入了检查业务类型的while循环的无限循环中。 Changing that to an if statement fixes it. 将其更改为if语句即可解决。

In addition, when you use and, or, or some other operator, you have to specify the variable again you are comparing. 此外,当使用and或or或其他运算符时,必须再次指定要比较的变量。

Your while statement that reads the lines of the file should look like this: 您的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()

Output: 输出:

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

The main problem is that your while loops should be simply if statements: 主要的问题是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

The reason your while loops never terminate is two reasons: You never read the next line inside that inner loop, and a populated string like 'b' will evaluate like True : 你的理由while环路从来没有终止的原因有二:你永远不读了内环的下一行,像一个人口稠密的字符串'b'将评估像True

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

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

The str.lower() will lowercase the string, so 'R'.lower() returns 'r' . str.lower()将小写字符串,因此'R'.lower()返回'r' Otherwise there is no break condition for the while and it will spin forever. 否则,没有break的条件while ,它会永远旋转。

Some other suggestions: 其他一些建议:

1) When opening files, using with eliminates the need to explicitly open and close files: 1)打开文件时,使用with无需显式openclose文件:

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

2) Explicitly calling fh.readline() isn't necessary, as you can iterate over an open file directly: 2) fh.readline()显式调用fh.readline() ,因为您可以直接迭代打开的文件:

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

This will also terminate when fh is empty, or you reach the end of the file, you might not get explicitly '' when the file is empty, and you no longer need the while loop fh为空或到达文件末尾时,这也将终止,当文件为空时,可能不会显式获得'' ,并且不再需要while循环

3) It's generally bad practice (but also hard to maintain) magic-number code. 3)这通常是不好的做法,但也很难维护。 For instance, what if the account number doesn't have exactly 5 characters? 例如,如果帐号不完全是5个字符怎么办? A more succinct way to do this would be with str.split(' ') , which will split on spaces: 一种更简洁的方法是使用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

In total: 总共:


# 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