直接把列表存储在文件中,可读性不好。
修改代码:把数据输出到一个磁盘文件而不是显示在屏幕上(称为标准输出)。然后就可以采用一种更可用的格式保存数据。
标准输出(standard output):这是使用“print()” BIF代码写数据的默认位置,这通常是屏幕。在Python中,标准输出是指“sys.stdout”,可以从标准库中的“sys”模块导入。
nester.py
import sys
def print_lol(the_list,indent=False,level=0,fn=sys.stdout):
for element in the_list:
if isinstance(element ,list):
print_lol(element,indent,level+1,fn)
else:
if indent:
for tap_stop in range(level):
print("\t",end='',file = fn)
print(element,file = fn)
import nester
import os
os.chdir("D:\\Program Files\\Python\\test")
try:
data = open('scatch.txt')
man = []
woman = []
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 == 'Woman':
woman.append(line_spoken)
except ValueError:
pass
data.close()
except IOError:
print("The file is missing!")
try:
out_man = open("man_data.txt","w+")
out_woman = open("woman_data.txt","w+")
nester.print_lol(man,True,0,out_man)
nester.print_lol(woman,True,0,out_woman)
out_man.seek(0)
out_woman.seek(0)
out_man.read()
out_woman.read()
except IOError:
print("File error")
finally:
out_man.close()
out_woman.close()