信用卡交易数据文件的记录

通过检测和异常处理记录信用卡交易记录

打开一个信用卡交易的数据文件(carddata.txt),加载所有交易,包括解释的字符串。
加载数据如下:

previous balance
25
debits
21.64
541.24
25
credits
-25
-541.24
finance charge/late fees
7.30
5

读取信用卡的数据文件,并计算最终的余额。
同时还有一个处理过程的日志文件生成。
主要使用try-except语句检测异常。
代码如下:

# -*- coding: utf-8 -*-
"""
Created on Mon Aug 21 17:13:14 2017

@author: zhang
"""

#!/usr/bin/env python

def safe_float(object):
    try:
        retval = float(object)
    except (ValueError, TypeError), diag:
        retval = str(diag)
    return retval

def main():
    """handle all the data processing"""
    log = open('cardlog.txt', 'w')
    try:
        ccfile = open('carddata.txt','r')
    except IOError, e:
        log.write('no transactions in this month')
        log.close()
        return
    txns = ccfile.readlines()
    ccfile.close()
    total = 0.00
    log.write('account log:\n')

    for eachTxn in txns:
        result = safe_float(eachTxn)
        if isinstance(result, float):
            total += result
            log.write('current value:%.2f data...processed\n' % total)
        else:
            log.write('ignored: %s' % result)
    print '$%.2f (new balance)' % total
    log.close()

if __name__=='__main__':
    main()

运行的结果如下:

$58.94 (new balance)

日志文件如下:

account log:
ignored: could not convert string to float: previous balance
current value:25.00 data...processed
ignored: could not convert string to float: debits
current value:46.64 data...processed
current value:587.88 data...processed
current value:612.88 data...processed
ignored: could not convert string to float: credits
current value:587.88 data...processed
current value:46.64 data...processed
ignored: could not convert string to float: finance charge/late fees
current value:53.94 data...processed
current value:58.94 data...processed

你可能感兴趣的:(python&C++)