python模块之linecache

本文详细介绍了Python模块linecache的基本用法,包括getline、getlines、updatecache和clearcache等函数,以及如何从文件中获取指定行数据并进行缓存管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# -*- coding: utf-8 -*-
#python 27
#xiaodeng
#python模块之linecache


import linecache
'''
>>> help(linecache)
Help on module linecache:
FUNCTIONS
    checkcache = extended_linecache_checkcache(filename=None, orig_checkcache=<function checkcache>)
        Extend linecache.checkcache to preserve the <pyshell#...> entries
        
        Rather than repeating the linecache code, patch it to save the
        <pyshell#...> entries, call the original linecache.checkcache()
        (skipping them), and then restore the saved entries.
        
        orig_checkcache is bound at definition time to the original
        method, allowing it to be patched.
    
    clearcache()
        Clear the cache entirely.
    
    getline(filename, lineno, module_globals=None)

DATA
    __all__ = ['getline', 'clearcache', 'checkcache'] 
'''


#从名为filename的文件中得到第lineno行。这个函数从不会抛出一个异常–产生错误时它将返回”(换行符将包含在找到的行里)。



#linecache.getline(filename,lineno)
#查找特定行(第一行)的数据,返回一个字符串
filename='1.txt'
re= linecache.getline(filename,1)
print re.strip()#因为本身带有换行符



#得到所有行数据,返回一个list
re= linecache.getlines(filename)
print re



#获取多少行的数据
re= linecache.getlines(filename)[0:4]
print re



#更新文件名为filename的缓存。如果filename文件更新了,使用这个函数可以更新linecache.getlines(filename)返回的列表
linecache.updatecache(filename)



#清理缓存
linecache.clearcache()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值