码迷,mamicode.com
首页 > 编程语言 > 详细

python:文本文件处理

时间:2015-12-06 14:29:38      阅读:136      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!