Python小程序:获取文本文件的所有内容

有时候希望获取一个文本文件的所有内容,但又不希望有打开文件、读文件、关闭文件这些繁琐的步骤,因此需要用一个小程序把这几个步骤封装起来,一句话完成所需要的获取文件内容的操作。为此,这里给出一个示例代码。


代码如下(get_text_file.py):

[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #! /usr/bin/env python  
  2.   
  3. import os  
  4.   
  5. ''''' 
  6. Get all the content of the file of the specified text file. 
  7.  
  8. Input: filename - the filename of the text file  
  9. Return: content - string. all the content of filename.  
  10.         If the filename not a valid regular file, then return None, and error information is printed. 
  11. '''  
  12. def get_text_file(filename):  
  13.     if not os.path.exists(filename):  
  14.         print("ERROR: file not exit: %s" % (filename))  
  15.         return None  
  16.   
  17.     if not os.path.isfile(filename):  
  18.         print("ERROR: %s not a filename." % (filename))  
  19.         return None  
  20.   
  21.     f = open(filename, "r")  
  22.     content = f.read()  
  23.     f.close()  
  24.   
  25.     return content  

使用示例:

[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. >>> import get_text_file  
  2. >>> content = get_text_file.get_text_file("./get_text_file.py")  
  3. >>> print(content)  
  4. #! /usr/bin/env python  
  5.   
  6. import os  
  7.   
  8. def get_text_file(filename):  
  9.         if not os.path.exists(filename):  
  10.                 print("ERROR: file not exit: %s" % (filename))  
  11.                 return None  
  12.   
  13.         if not os.path.isfile(filename):  
  14.                 print("ERROR: %s not a filename." % (filename))  
  15.                 return None  
  16.   
  17.         f = open(filename, "r")  
  18.         content = f.read()  
  19.         f.close()  
  20.   
  21.         return content  
  22.   
  23.   
  24.   
  25. >>> content = get_text_file.get_text_file("not_exist_filename")  
  26. ERROR: file not exit: not_exist_filename  
  27. >>> exit()  

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值