python 檔案讀寫練習

weixin_34308389發表於2017-10-23
#!/usr/bin/python
#對檔案進行讀寫操作練習,將陳智濤和客服的對話分開,分別存到customer和service檔案>中,並且遇到========,就對檔案加1,重新寫入
def fileSave(filename,content,count):
    filename = filename+'_'+str(count)+'.txt'
    f = open(filename,'w')
    f.writelines(content)
    f.close()
def splitFile(filename):
    f = open('record.txt')
    customer = []
    service = []
    count = 1
    for line in f:
        if line[:6] != '======' and line.strip() != '':
            (role,record) = line.split(':',1)
            if '陳智濤'== role:
                customer.append(record)
            if '客服' == role:
                service.append(record)
        else:
            fileSave('customer',customer,count)
            fileSave('service',service,count)
            customer = []
            service = []
            count +=1

    fileSave('customer',customer,count)
    fileSave('service',service,count)
    f.close()

splitFile('record.txt')

相關文章