Python 文件读取和打印,有异常和终止

标签 python python-3.x

您好,我是一名自学 Python 的新程序员。我遇到了一个非常有趣的问题,需要一些帮助来为其创建一个程序。事情是这样的

酒店销售人员在文本文件中输入销售额。每行包含以下内容,以分号分隔:客户姓名、销售的服务(例如晚餐、 session 、住宿等)、销售金额以及该事件的日期。编写一个程序来读取此类文件并显示每个服务类别的总金额。如果文件不存在或格式不正确,则显示错误。

  • 提示输入要处理的文件名称并发出 如果无法打开该文件,则显示错误消息并终止

  • 验证每行的项目数量是否正确,并且 如果不存在则终止

  • 验证美元金额是否为有效的 float 编号,如果不是则终止

  • 保留遇到的类别的列表(它们 可能与下面的不同)和另一个列表 每个类别的累计美元金额。这是两个 列表,但其中的元素与 中的元素相关 另一个(按位置)

  • 处理完所有数据后关闭文件

  • 显示类别和每个类别的总数

我们的示例文本文件看起来像这样

Bob;Dinner;10.00;January 1, 2015
Tom;Dinner;14.00;January 2, 2015
Anne;Lodging;125.00;January 3, 2015
Jerry;Lodging;125.00;January 4, 2015

这就是我正在尝试做的事情。我正在尝试了解这一点,并在学习时得到 Stack Overflow 专家的帮助来解决这个问题。谢谢大家!

import sys
def main():

    try:
        line = infile.readline()
        for line in infile:
            inputFileName = input("Input file name: ")
            infile = open(inputFileName, "r")
            fields = line.split(";")

            value = float(fields[1])

    except:
        print("Error: The file cannot be opened.")
        sys.exit(1)

infile.close()
main()

最佳答案

这是一个基本草图。这未经测试,因此可能包含拼写错误、逻辑错误等。此外,它不会检查您提到的所有错误情况。但是,这应该足以让您开始使用。主要技巧就是 throw an exception遇到错误的地方,以及 catch it你可以在哪里处理它。这会立即停止按您想要的方式处理文件。另一个技巧是保留 dictionary将类别映射到总计,以便您可以按类别保存运行总计。

def main():
    # Req 1.1: ask for a filename
    file_name = input("Input file name: ")
    try:
        # To keep things simple we do all the file processing
        # in a separate function. That lets us handle
        # any error in the file processing with a single
        # except block
        amount_by_category = process_file(file_name)
        # Req 6: display the categories - python will
        # display the contents of a data structure when we print() it
        print('Totals: ', amount_by_category)
    except Exception, e:
        # Reqs 1-3: display errors
        print('Error processing file:', e)

def process_file(file_name):
        # Req 1.2: open the file
        infile = open(file_name, 'r')
        # Req 4.1: somewhere to remember the categories
        amount_by_catgeory = {}
        # Reqs 2-4: we are dealing with a many line file
        # Req 5: when we reach the end, python closes the file for us automatically
        for line in infile:
            # Req 2.1: each line should have 4 values separated by ;
            fields = line.split(';')
            # Req 2.2: does this line have 4 values?
            if len(fields) != 4:
                raise Exception('Expected 4 fields but found %s' % len(fields))
            # Req 3: is the third value a number?
            value = float(fields[2])
            # Req 4.2: what category does this line belong to?
            category = fields[1]
            # Req 4.3.1: have we seen this category before?
            if not category in amount_by_category:
                # Req 4.3.2: accumulations start from 0?
                amount_by_category[category] = 0.0f
            # Req 4.4: increase the cumulative amount for the category
            amount_by_category[category] += value

        return amount_by_category

关于Python 文件读取和打印,有异常和终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33113860/

相关文章:

python - 如何在区域上方激活功能,在限制区域外保持事件状态

python - instagram.bind.InstagramClientError : Unable to parse response, 无效的 JSON

python-3.x - 无法访问 Google Colaboratory 中的 csv 文件

python-3.x - 使用 setuptools 在 python 包中链接 f2py 生成的 *.so 文件

python-3.x - 如果给定列表中的值存在于多列中并计算列数

python - 如何使用 mypy 的内部类型检查功能?

python - 波开 : redirect stderr and stdout to single stream

python - 使用 Python 的 Scipy DCT-II 进行 2D 或 ND DCT

python - 为什么 QTimer 不能在对象中工作? python PyQt

python-3.x - 如何用一个滚动条滚动两个并行的文本小部件?