python:文本文件处理

# coding=utf-8

#将列表写入文件 :'w+'(覆盖原有文件内容),'a+'(在原文件的基础上追加)
def write_list_test(path,savelist,pattarn):
    try:
        f = open(path, pattarn)
    except IOError:
        print "The file don't exist, Please double check!"
        exit()
        
    try:
        f.writelines(savelist)
        print '保存成功!!!'
    finally:
        f.close()

#将字符串写入文件
def write_str_test(path,savestr,pattarn):
    try:
        f = open(path, pattarn)
    except IOError:
        print "The file don't exist, Please double check!"
        exit()
        
    try:
        f.write(savestr)
        print savestr, '保存成功!!!'
    finally:
        f.close()
        
#检测文件是否关闭
def check_close(fsock):
    S1 = fsock.closed
    if True == S1:
        print 'the file is closed'
    else:
        print 'The file donot close'
    return S1

#从指定路径下读入文件      
def read_txt_test(path,pattarn):
    try:
        f = open(path, pattarn)
    except IOError:
        print "The file don't exist, Please double check!"
        exit()
        
    try:
#         all_text=f.read()#读入文件的所有内容
#         print all_text
        
#         lines=f.readlines()
#         for key in lines:
#             print key.strip()
            
            
        for line in f:#按行的方式读入文件内容
            print line.strip()#strip除去空格,Tab和换行
    finally:
        f.close()

if __name__ == '__main__':
#     li = ["helloword
", "hellochina
"]
#     write_list_test('hello.txt',li,'a+')  
#     write_str_test('helloword.txt',"helloword
", 'a+')    
#     write_str_test('helloword.txt',"helloword
", 'a+')    
    read_txt_test('helloword.txt', 'r')
原文地址:https://www.cnblogs.com/dmir/p/5023386.html