zoukankan      html  css  js  c++  java
  • 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')
  • 相关阅读:
    redhat6.4 数据包无法到达
    hibernate-Table 'XXX.XXX' doesn't exist
    LeetCode 之 TwoSum
    vim 中的常用编辑
    linux sed 批量替换多个文件中的字符串
    RedHat 6.4企业版利用iso镜像做本地yum源
    win7 vmware虚拟机上网设置
    virtualbox ubuntu下ssh连接
    Source Insight 插件
    非递归排序
  • 原文地址:https://www.cnblogs.com/dmir/p/5023386.html
Copyright © 2011-2022 走看看