zoukankan      html  css  js  c++  java
  • python 操作txt 生成新的文本数据

    name: Jack   ;    salary:  12000
     name :Mike ; salary:  12300
    name: Luk ;   salary:  10030
      name :Tim ;  salary:   9000
    name: John ;    salary:  12000
    name: Lisa ;    salary:   11000

     将数据file1,转化成file2并且有扣税和实际收入字段的数据

    实现第一种:读写都是操作txt文本

    inFileName = 'file.txt'
    outFileName = 'file2.txt'
    
    with open(inFileName) as ifile, open(outFileName, 'w') as ofile:
        # beforeTax = ifile.read().splitlines()
        # or we could use
        beforeTax = ifile.read().split('
    ')
        for one in beforeTax:
            # print(open)
            if one.count(';') != 1:  # ensure valid
                continue
            namePart, salaryPart = one.split(';')
            if namePart.count(':') != 1:  # ensure valid
                continue
            if salaryPart.count(':') != 1:  # ensure valid
                continue
    
            name = namePart.split(':')[1].strip()
            # salary = int(salaryPart.split(':').strip())  #lies对象没有strip属性,所以得取索引
            salary = int(salaryPart.split(':')[1].strip())
            # print(salaryPart)
    
            income = int(salary * 0.9)
            tax = int(salary * 0.1)
    
            outPutStr = 'name: {}   ;    salary:  {} ;  tax: {} ; income:  {}'.format(name, salary, tax, income)
    
            print(outPutStr)
            
            ofile.write(outPutStr + '
    ')
    name: Jack   ;    salary:  12000 ;  tax: 1200 ; income:  10800
    name: Mike   ;    salary:  12300 ;  tax: 1230 ; income:  11070
    name: Luk   ;    salary:  10030 ;  tax: 1003 ; income:  9027
    name: Tim   ;    salary:  9000 ;  tax: 900 ; income:  8100
    name: John   ;    salary:  12000 ;  tax: 1200 ; income:  10800
    name: Lisa   ;    salary:  11000 ;  tax: 1100 ; income:  9900
  • 相关阅读:
    python多版本切换
    python之禅
    Python int与string之间的转化
    pycharm工具使用
    python学习路线图
    traceback.print_exc()的用法
    他人学习Python感悟
    【西北师大-19软工】第十三、十四次作业汇总暨期末总结
    【西北师大-19软工】第十二次作业成绩汇总
    第十七周助教工作总结——NWNU李泓毅
  • 原文地址:https://www.cnblogs.com/chevron123/p/13018988.html
Copyright © 2011-2022 走看看