首页 > 编程语言 > 详细

python:文本文件处理

时间:2015-12-06 14:28:15      阅读:275      评论:0      收藏:0      [点我收藏+]
# 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\n", "hellochina\n"]
#     write_list_test(‘hello.txt‘,li,‘a+‘)  
#     write_str_test(‘helloword.txt‘,"helloword\n", ‘a+‘)    
#     write_str_test(‘helloword.txt‘,"helloword\n", ‘a+‘)    
    read_txt_test(helloword.txt, r)

python:文本文件处理

原文:http://www.cnblogs.com/dmir/p/5023386.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!