file - a simple task

2016.12.16

 

The general file is divided into three parts: input, processing and output.

Below is a table of related documents.


 

How to open files

handle = open(file_name,access_mode='r')

The file_name variable contains the string name of the file we wish to open. In access_mode, 'r' means read, 'w' means write, and 'a' means add. '+' means read and write, 'b' means binary access. If access_mode is not provided, the default value is 'r'. If the open is successful, a file object handle will be returned. When a file is returned, we can access some of its methods, such as readlines() and close().

Task: Divide the data in the file ( record.txt ) and save it according to the following rules:
The dialogue of the small turtle is saved as a boy_*.txt file (remove the "small turtle : ")
The conversation of the customer service is saved as a girl_*.txt file separately (remove the "customer service : ")

 

There are a total of three dialogues in the file, which are saved as boy_1.txt, girl_1.txt , boy_2.txt, girl_2.txt, boy_3.txt, gril_3.txt, a total of 6 files (hint: different dialogues in the file have been used "" ========== " split )

 

For a file, write a program as follows:

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('record.txt')

    boy = []
    girl = []
    count = 1

    for each_line in f:
        if each_line[:6] != '======':
            (role, line_spoken) = each_line.split(':', 1)
            if role == 'little turtle':
                boy.append(line_spoken)
            if role == 'small customer service':
                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')

 After running, several files in the form of txt can be generated in the same file. Note that the place where the code is generated should be with the place where the file is. This will open and read the file.

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326944071&siteId=291194637