《python》学习笔记(Day2),读入磁盘文件,经过处理,保存成相应的磁盘文件

一、print_lol函数。

"""This is the standard way to include a multiple-line comment in your code.这个模块,提供了一个名为print_lol的函数,这个函数的作用是打印列表,其中可能包含嵌套列表。"""
import sys
def print_lol(the_list,indent=False,level=0,fh=sys.stdout):
"""函数的第一个位置参数,可以是任何python列表。指定列表中的每个数据项会递归的输出在屏幕上,各数据项各占一行。第二个参数是默认情况下不打开缩进。第三个参数用于在遇到嵌套列表时插入制表符。第四个参数用来标识数据写入的位置,为一个文件对象。"""
for each_item in the_list:
        if isinstance(each_item,list):
            print_lol(each_item,indent,level+1,fh)
        else:
            if indent:
                for tab_stop in range(level):
                    print>>fh,'\t',
                   print>>fh,each_item

二、磁盘文件处理代码。

import os

import nester
os.chdir('C:\\Python27\\HeadFirstPython\\chapter3')   
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 DATA FILE IS MISSING!!'
try:
        with open('man_data.txt','w')as man_file:
                nester.print_lol(man,fh=man_file)
        with open('other_data.txt','w')as other_file:
                nester.print_lol(other,fh=other_file)
except IOError as err:

        print 'File error:'+str(err)




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值