We want to implement a file read and write operation of a small program
First we have a file
We want to "============" as the boundary, each role is divided into a separate TXT file, according to the split line is divided into
Xiaona_1.txt Xiaobing_1.txt
Xiaona_2.txt Xiaobing_2.txt
Four files in such a format
The following code:
#定义一个保存文件的函数def Save_file (xiaona,xiaobing,count): file_name_xiaobing = ' Xiaobing_ ' +str (count) + '. txt ' #组织文件名 File_nam E_xiaona = ' Xiaona_ ' +str (count) + '. txt ' #组织文件名 xiaobing_file = open (file_name_xiaobing, ' W ') #文件写入操作 no file created Xiaona_fil E = open (File_name_xiaona, ' W ') Xiaobing_file.writelines (xiaobing) #写入内容 xiaona_file.writelines (Xiaona) xiaoBing_f Ile.close () xiaona_file.close () #定义分割文件的函数def split_file (file_name): F = open (file_name) #打开文件 xiaobing = [] #定义接受 Array of creep sessions Xiaona = [] #定义接受小娜会话的数组 count = 1 #定义文件数 for each_line in f:if each_line[:6]!= ' ====== ': (role,speakcontent) = Each_line.split (': ', 1) #split函数前面一个参数表示分割符号 The following one indicates the number of splits if role = = ' Creeps ': Xiaobing.append (speakcontent) if role = = ' Cortana ': Xiaona.append (speakcontent) Else: #保存文件 save_file (xiaona,xiaobing,count) #重新初始化一下 xiaobing = [] Xiaona = [] Count + =1 #因为分割符号 "======" in the last one. So here's what to save the last file Save_file (xiaona,xiaobing,count) f.close () #调用函数执行功能split_f Ile (' Record.txt ')
Finally attach the implementation effect
Python (iii) a small program for file read and write operations