python中print又可将数据写入文件_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("\t",end='',file=where)

print(each_item,file=where)

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

C:\Users\eric\Documents\Python\nester>c:\Users\eric\AppData\Local\Programs\Python\Python35-32\python.exe setup.py install

running install

running build

running build_py

copying nester.py -> build\lib

running install_lib

copying build\lib\nester.py -> c:\Users\eric\AppData\Local\Programs\Python\Python35-32\Lib\site-packages

byte-compiling c:\Users\eric\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\nester.py to nester.cpython-35.pyc

running install_egg_info

Removing c:\Users\eric\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\iamericnester-1.6.1-py3.5.egg-info

Writing c:\Users\eric\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\iamericnester-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))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值