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().
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.