Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python文件读取和打印,包括异常和终止_Python_Python 3.x - Fatal编程技术网

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

Python文件读取和打印,包括异常和终止,python,python-3.x,Python,Python 3.x,你好,我是一个非常新的程序员,自学Python。我遇到了一个非常有趣的问题,需要一些帮助来创建一个程序。事情是这样的 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 酒店销售人员在文本文件中输入销售额。每行包含以下内容,以分号分隔:客户名称、销售的服务(如晚餐、会议、

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

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
酒店销售人员在文本文件中输入销售额。每行包含以下内容,以分号分隔:客户名称、销售的服务(如晚餐、会议、住宿等)、销售金额和活动日期。编写一个程序来读取这样一个文件,并显示每个服务类别的总金额。如果文件不存在或格式不正确,则显示错误

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

  • 验证每一行的项目和数量是否正确 如果没有,则终止

  • 验证美元金额是否为有效的浮点值 编号,如果没有,则终止

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

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

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

我们的示例文本文件如下所示

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
这就是我要做的。我试图了解这一点,并从堆栈溢出方面的专家那里得到一些帮助,以便在学习过程中解决这个问题。谢谢大家

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

这是一个基本的草图。这是未经测试的,因此可能包含打字错误、逻辑错误等。此外,它不会检查您提到的所有错误条件。然而,这应该足以让你开始。主要的技巧是确定在哪里遇到错误,以及在哪里可以处理错误。这会立即停止处理您想要的文件。另一个技巧是将一个类别映射到total,这样您就可以按类别保留一个正在运行的total

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阅读文本文件,所以我不确定如何正确处理这个问题。然后这个问题就太模糊了。好吧,谢谢你过来看看。简单的过程:对于每个“做点什么或失败”部分,试着给出属于“失败”的程序输入,并查看当我输入错误的文件名时,我成功地显示了错误消息。如何打印输出?它通过以下行打印:
print('Totals:',amount\u by\u category)
。那会有点难看,但可读性很强。如果你想要更好的东西,你必须多写一些代码。可能类似于
对于category,value in amount\u by\u category.items():print(%s的值是%s%%(category,value))
您可以将其添加到代码中,使其更具可操作性吗?当它成为一个工作程序时,我真的学得更好。用Python读取文件对我来说是非常新的。@CainBoozer我希望这里有足够的内容让你开始学习。如果你想调整程序以改进格式等,请随意这样做。由于这个网站的目的是真正回答有针对性的问题,而不是为某人制作一个完整的工作程序,我将把东西留在这里。如果您觉得这个答案有帮助,请将其标记为正确和/或向上投票,我们将不胜感激。好的,我理解。谢谢你的意见。我会提高投票率,但我的声誉很低。