文件对象-读操作

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值