1、读取文件,将所有的信息存储在一个大字符串中
file_object = open("ClassPathXmlApplicationContext.java",'r') #创建一个文件对象,也是一个可迭代对象
try:
all_the_text = file_object.read() #结果为str类型
print type(all_the_text)
print "all_the_text=",all_the_text
finally:
file_object.close()
2、读取每行字符串,存储在一个列表中
file_object1 = open("ClassPathXmlApplicationContext.java",'r')
try:
list_of_all_the_lines = file_object1.readlines() #读取的每行文本后面加上了'\n'
print "list_of_all_the_lines:",list_of_all_the_lines
finally:
file_object1.close()
help(str.splitlines)
file_object2 = open("ClassPathXmlApplicationContext.java",'r')
try:
list_of_all_the_lines1 = file_object2.read().splitlines()
print "list_of_all_the_lines1:",list_of_all_the_lines1
finally:
file_object2.close()
3、使用循环遍历文件对象,文件对象是一个可迭代对象
file_object3 = open("ClassPathXmlApplicationContext.java",'r')
try:
ii = 0
for line in file_object3:
ii = ii + 1
line = line.rstrip( )
print ii,line
finally:
file_object3.close()
4、从文件中读取指定的行,使用内置模块linecache
import linecache
print dir(linecache)
help(linecache.getline)
for i in xrange(10):
theline = linecache.getline("ClassPathXmlApplicationContext.java", i+1)
print "%d theline= %s" % (i+1,theline)
5、计算文件的行数
"""
文件较大时,影响性能
"""
file_object4 = open("ClassPathXmlApplicationContext.java",'r')
try:
count = len(file_object4.readlines())
print "count=",count
finally:
file_object4.close()
"""
优化性能的方法
"""
count = -1
for count,line in enumerate(open("ClassPathXmlApplicationContext.java",'rU')):
"""
enumerate(iterator[,start]) -> return iterator object for index,value
"""
print "%d,%s" % (count,line)
count += 1
print "count=",count