当前位置: 移动技术网 > IT编程>脚本编程>Python > Python小程序:获取文本文件的所有内容

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

2019年04月19日  | 移动技术网IT编程  | 我要评论

bavii,遗传学歌剧,歪鼻矫正费用

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


代码如下(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()


如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网