Python小程序:获取文本文件的所有内容
2014-02-28 19:55
459 查看
有时候希望获取一个文本文件的所有内容,但又不希望有打开文件、读文件、关闭文件这些繁琐的步骤,因此需要用一个小程序把这几个步骤封装起来,一句话完成所需要的获取文件内容的操作。为此,这里给出一个示例代码。
代码如下(get_text_file.py):
使用示例:
代码如下(get_text_file.py):
#! /usr/bin/env python import os ''' Get all the content of the file of the specified text file. Input: filename - the filename of the text file Return: content - string. all the content of filename. If the filename not a valid regular file, then return None, and error information is printed. ''' def get_text_file(filename): if not os.path.exists(filename): print("ERROR: file not exit: %s" % (filename)) return None if not os.path.isfile(filename): print("ERROR: %s not a filename." % (filename)) return None f = open(filename, "r") content = f.read() f.close() return content
使用示例:
>>> import get_text_file >>> content = get_text_file.get_text_file("./get_text_file.py") >>> print(content) #! /usr/bin/env python import os def get_text_file(filename): if not os.path.exists(filename): print("ERROR: file not exit: %s" % (filename)) return None if not os.path.isfile(filename): print("ERROR: %s not a filename." % (filename)) return None f = open(filename, "r") content = f.read() f.close() return content >>> content = get_text_file.get_text_file("not_exist_filename") ERROR: file not exit: not_exist_filename >>> exit()
相关文章推荐
- Python小程序:获取二进制文件的所有内容
- Python获取Redis所有Key以及内容
- python中获取指定目录下所有文件名列表的程序
- python中获取指定目录下所有文件名列表的程序
- Python获取Redis所有Key以及内容
- Python—itchat小程序之——景点信息获取
- 使用c#获取access中所有表的表名与内容
- 按行获取文本文件的内容
- python获取网页所有链接
- 编写一个Python程序,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径
- 使用python获取系统所有进程PID以及进程名称
- Python爬虫实战入门五:获取JS动态内容—爬取今日头条
- Java一次读取文本文件所有内容(已知编码)
- python 执行c 程序解析 xml 写入文本文件统计程序
- python 获取一周的天气内容
- python爬虫爬取csdn博客专家所有博客内容
- C# WinFrom(CS)程序调用 WEB 站点,获取响应内容
- 微信小程序 textarea 复制一大段内容粘贴到内容框,所有文字会往上推,在页面上看不到内容
- 获取指定目录(包含子目录)下所有的txt文件的个数,并打印文件名称。程序1。
- python_获取网页的内容和状态