首页 > 编程语言 > 详细

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

时间:2014-03-01 13:52:14      阅读:538      评论:0      收藏:0      [点我收藏+]

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


代码如下(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小程序:获取文本文件的所有内容,布布扣,bubuko.com

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

原文:http://blog.csdn.net/a_flying_bird/article/details/20154335

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!