Python文件操作

来源:互联网 发布:Java秒数转换时间格式 编辑:程序博客网 时间:2024/05/09 09:17

最近博主在自学Python,特此记录感觉很有意思的Python基础代码,知识层面有欠缺,希望大家多多包涵大笑


Python文件操作:

文件内容1.txt

A:I Love You
B:I Love You Too
==============================================
A:I Hate You
B:L Hate You Too
==============================================
A:Playing Game
B:Playing Game Too


在次实现已‘============’为分隔将不同对话写入不同.txt中,例如A_1.txt,A_2.txt,A_3.txt,B_1.txt,B_2.txt,B_3.txt


具体代码如下:

<span style="font-size:18px;"><strong>def save_file(A, B, count):    file_name_A = 'A_'+str(count)+'.txt'    file_name_B = 'B_'+str(count)+'.txt'    A_file = open(file_name_A, 'w')    B_file = open(file_name_B, 'w')    A_file.writelines(A)    B_file.writelines(B)    A_file.close()    B_file.close()def split_file(file_name):    f = open(file_name)    A = []    B = []    count = 1    for each_line in f:        if each_line[:6] != '======':            #进行字符串分割            (role, line_spoken) = each_line.split(':', 1)            #split(sep=None, maxsplit = 1)切片方法            if role == 'A':                A.append(line_spoken)            if role == 'B':                B.append(line_spoken)        else:            #文件的分别保存            save_file(A, B, count)            A = []            B = []            count += 1    save_file(A, B, count)    f.close()    split_file('1.txt')        </strong></span>

输出结果在文件夹中显示:


0 0