• Python 通过print_lol将数据保存到文件中


    1. 定义一个print_lol函数来控制列表的缩进和写入位置

    import sys
    """this is a new fuction, which work for a list"""
    def print_lol(the_list,indent=False,level=0,where=sys.stdout):
        """ one arguement is the_list"""
        for each_item in the_list:
            if isinstance(each_item,list):
                print_lol(each_item,indent,level+1,where)
            else:
                if indent:
                        for tab_stop in range(level):
                            print("	",end='',file=where)
                print(each_item,file=where)
    

    2. 将更新的代码安装到本地库

    C:UsersericDocumentsPython
    ester>c:UsersericAppDataLocalProgramsPythonPython35-32python.exe setup.py install
    running install
    running build
    running build_py
    copying nester.py -> buildlib
    running install_lib
    copying buildlib
    ester.py -> c:UsersericAppDataLocalProgramsPythonPython35-32Libsite-packages
    byte-compiling c:UsersericAppDataLocalProgramsPythonPython35-32Libsite-packages
    ester.py to nester.cpython-35.pyc
    running install_egg_info
    Removing c:UsersericAppDataLocalProgramsPythonPython35-32Libsite-packagesiamericnester-1.6.1-py3.5.egg-info
    Writing c:UsersericAppDataLocalProgramsPythonPython35-32Libsite-packagesiamericnester-1.6.1-py3.5.egg-info
    

    3. 前段代码格式化文件内容并分割将内容存入man和other两个对象,后段代码以写模式打开2个新的文件并man和other对象存入其中。(存入的过程中调用print_lol进行格式再处理)

    import nester
    import sys
    man = []
    other = []
    try:
        data = open('sketch.txt')
        for each_line in data:
            try:
                (role, line_spoken) = each_line.split(':',1)
                line_spoken=line_spoken.strip()
                if role== 'Man':
                    man.append(line_spoken)
                elif role == 'Other Man':
                    other.append(line_spoken)
            except ValueError:
                pass
        data.close()
    except IOError:
        print ('The datafiel is missing!')
        
    try:
        with open('man_data.txt','w') as man_file:
            nester.print_lol(man,where=man_file)
    
        with open('other_data.txt','w') as other_file:
            nester.print_lol(other,where=other_file)
    
        
    except IOError as err:
        print('file error:' +str(err))
    
  • 相关阅读:
    澳洲中产收入水平[转]
    [转载]在澳洲做IT人士的收入差别
    取消excel 工作保护 密码的宏
    SAP ML 物料分类账详解(含取消激活物料帐方法)
    ABAP--如何创建自定义打印条码
    SAP 产品条码WMS结合 以及ABAP script的集成 BarCode
    SAP 以工序为基准进行发料 机加工行业 Goods Issue to Routing
    SAP HR模块的基础数据表和增强配置
    SAP财务供应链与金库管理的联系与区别
    评点SAP HR功能及人力资源管理软件
  • 原文地址:https://www.cnblogs.com/oskb/p/4835751.html
Copyright © 2020-2023  润新知