用Python打印

2024-06-16 13:19:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我在写一个程序,用户在一个文本文件中输入销售额,程序读取该文件并打印出每个销售类别的总金额。下面是一个文本文件的示例:

Alice;Lodging;49.99;10/12/2016
Bob;Dining;8.42;10/13/2016
Charles;Lodging;55.76;10/14/2016
David;Dining;19.95;10/15/2016
Eve;Rental;105.99;10/16/2016
Frank;Rental;raft;10/17/2016

程序必须有两个例外:文件名错误的IOError和无法将数量解析为float的ValueError。对于ValueError,程序必须继续跳过该行。你知道吗

以下是我目前的代码:

from collections import defaultdict

my_dict = defaultdict(float)
filename = str(input(("Sales file: ")))
  try:
  with open(filename) as f:
    for line in f.readlines():
        _, key, val, _ = line.split(';')
        try:
            my_dict[key] += float(val)
        except ValueError:
            print ('The amount %s, cannot be converted to a float!', line.strip())
except IOError:
    print ("No such file or directory:", filename)
    sys.exit()

每次我运行它,我都会得到:

Sales file: sales.txt
The amount %s, cannot be converted to a float! Frank;Rental;raft;10/17/2016

我的代码怎么了?你知道吗


Tags: frank代码程序linefloatfilenamefile文本文件
3条回答

回答这个问题让人觉得很愚蠢,但在Frank;Rental;raft;10/17/2016中的“raft”是导致错误的原因。 如果您有与此相关的其他问题,请说出来,以便我们可以回答。为什么“木筏”在那里?你知道吗

你的代码没有问题。实际上问题就在你的档案里。文件最后一行中第三个字段的格式数据不正确。因此,当您尝试将字符串转换为float时,会出现异常,因为该值不适合将其转换为float。你知道吗

from collections import defaultdict

my_dict = defaultdict(float)
filename = str(input(("Sales file: ")))
try:
    with open(filename) as f:
      for line in f.readlines():
        _, key, val, _ = line.split(';')
        try:
            my_dict[key] += float(val)
        except ValueError:
            print ('The amount %s, cannot be converted to a float!' % val, line.strip())
except IOError:
    print ("No such file or directory:", filename)
    sys.exit()

你忘了格式化字符串。试试这个:

print ('The amount %s, cannot be converted to a float!' % val, line.strip())

注意% val。你知道吗

相关问题 更多 >