Python小程序:获取文本文件的所有内容
来源:互联网 发布:淘宝佣金查询 编辑:程序博客网 时间:2024/05/16 07:08
有时候希望获取一个文本文件的所有内容,但又不希望有打开文件、读文件、关闭文件这些繁琐的步骤,因此需要用一个小程序把这几个步骤封装起来,一句话完成所需要的获取文件内容的操作。为此,这里给出一个示例代码。
代码如下(get_text_file.py):
#! /usr/bin/env pythonimport 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 Noneif not os.path.isfile(filename):print("ERROR: %s not a filename." % (filename))return Nonef = 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 pythonimport osdef 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()
0 0
- Python小程序:获取文本文件的所有内容
- Python小程序:获取文本文件的所有内容
- Python小程序:获取二进制文件的所有内容
- Python脚本程序实现搜索文本文件内容
- 按行获取文本文件的内容
- 从网页中爬取小说内容并保存为文本文件的小程序
- python检索特定内容的文本文件
- python检索特定内容的文本文件2
- Python获取Redis所有Key以及内容
- 获取元素的所有内容
- 一次读取文本文件的所有内容到std::string
- python 读取文本文件内容转化为python的list
- python 读取文本文件内容转化为python的list
- Java 小例子:按指定的编码读取文本文件内容
- Java 小例子:按指定的编码读取文本文件内容
- 从html页面获取纯文本文件替换其中的内容
- 小程序:获取动态库/程序依赖的所有动态库
- 使用PHP程序直接调用文本文件的内容
- 道路和航路 Java实现
- 如何在cmd命令行中查看、修改、删除与添加,设置环境变量
- Android将日志信息自动发送到指定的邮箱中 邮件的内容以附件形式发送
- 求高人指点:wikioi 2171 棋盘覆盖
- @注解_复合主键
- Python小程序:获取文本文件的所有内容
- Android将应用log信息保存文件
- UVa:11383 Golden Tiger Claw(KM算法)
- SSH2框架搭建 和 配置文件详解
- UVA 11387 (14.2.28)
- MFC应用程序中指针的使用
- Android将程序崩溃信息保存本地文件
- 一些常用算法模板
- virtualbox的使用心得