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\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')
作者:奋斗的珞珞
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.