Python (iii) a small program for file read and write operations

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.