1 文件的打开方式:
r | 以只读方式打开 |
w | 以写入方式打开文件,会覆盖已存在的文件 |
x | 用词方式打开文件,如果文件已存在,会发生异常 |
a | 一些如模式打开,如文件存在,在文件末尾追加写入 |
b | 以二进制打开文件 |
t | 以文本模式打开 |
+ | 可读写模式 |
u | 通用换行符支持 |
2 任务:
将文件(record)中数据进行分割并按照以下规则保存:
--涛涛的对话单独保存为boy_*.txt文件(去掉 涛涛:)
--星星的对话单独保存为girl_*.txt文件(去掉 星星:)
--文件总共三段对话分别保存为boy_1.txt, girl_1.txt, boy_2.txt, girl2_txt, boy_3.txt, girl_3.txt 6个文件(去掉文件中的“=====...”)
重要方法:
①split(sep=None, maxsplit=-1):
不带参数默认以空格为分隔符切片字符串,如果maxsplit参数有设置,则仅分隔maxsplit个字符串,返回切片后的字符串拼接的列表。
②文件对象的内置方法:f.writelines(seq):
向文件写入字符串序列seq,seq应该是一个返回字符串的可迭代对象。
f = open('record.txt',encoding='utf-8')
boy = []
girl = []
count = 1
for each_line in f:
if each_line[:6] != '======':
#如果前6个不是“======”,进行字符串分割操作
(role,line_spoken)= each_line.split(':',1)
if role == '涛涛':
boy.append(line_spoken)
if role == '星星':
girl.append(line_spoken)
else:
#文件的保存操作
file_name_boy = 'boy_' + str(count) + '.txt'
file_name_girl = 'girl_' + str(count) + '.txt'
boy_file = open(file_name_boy,'w')
girl_file = open(file_name_girl,'w')
#写入
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
boy = []
girl =[]
count += 1
#因为只有两行“=======”,会导致最后一段对话不会写人。
file_name_boy = 'boy_' + str(count) + '.txt'
file_name_girl = 'girl_' + str(count) + '.txt'
boy_file = open(file_name_boy,'w')
girl_file = open(file_name_girl,'w')
#写入
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
f.close()
运行结果
代码优化:
def save_file(boy,girl,count):
file_name_boy = 'boy_' + str(count) + '.txt'
file_name_girl = 'girl_' + str(count) + '.txt'
boy_file = open(file_name_boy,'w')
girl_file = open(file_name_girl,'w')
#写入
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
def split_file(file_name):
f = open(file_name,encoding='utf-8')
boy = []
girl = []
count = 1
for each_line in f:
if each_line[:6] != '======':
#如果前6个不是“======”,进行字符串分割操作
(role,line_spoken)= each_line.split(':',1)
if role == '涛涛':
boy.append(line_spoken)
if role == '星星':
girl.append(line_spoken)
else:
#文件的保存操作
save_file(boy,girl,count)
boy = []
girl =[]
count += 1
#因为只有两行“=======”,会导致最后一段对话不会写人。
save_file(boy,girl,count)
f.close()
split_file('record.txt')