python操作文本_python操作文本

本文主要介绍了Python操作文本文件的方法。通过open()函数打开文件句柄,可进行读写操作,如write()写入、read()读取等,还能使用seek()重置指针。同时介绍了标准库linecache,可通过getline()获取指定行内容、getlines()获取所有行内容。

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

python打开一个文件的句柄用open()>>> d = open('a.txt','w') #w write r read a append

>>> d.write('hi.\nsecond hi.')

>>> d.close()

>>> d=open('a.txt','r')

>>> d.readline()

'hi.\n'

>>> d.readline() #一次读一行,指针会改变

'second hi.'

>>> d.readline() #一次读一行,指针会改变

''

>>> d.seek(0) #文本的指针重置为0

>>> d.read(100) #表示一次读100个字节

'hi.\nsecond hi.'

>>> a = open('tmp.txt','w') #文件不存在会自动创建

>>> a.write(1) #只能写字符串或者是字符流

Traceback (most recent call last):

File "", line 1, in ?

TypeError: argument 1 must be string or read-only character buffer, not int

>>> a.write("this is my apple!")

>>> a.close()

>>> b=open("tmp.txt",'r')

>>> b.read(500)

'this is my apple!'

>>> b.seek(0)

>>> b.readline()

'this is my apple!'

标准库的介绍 linecache>>> import linecache

>>> print linecache.getline("tmp.txt",1)

this is my apple!

>>> print linecache.getline("tmp.txt",2)

hhloo

>>> print linecache.getline("tmp.txt",3)

ni hoa

>>> lines=linecache.getlines("tmp.txt")

>>> lines

['this is my apple!\n', 'hhloo \n', 'ni hoa \n', 'hello\n', '\n']

>>> help(linecache) 查看帮助

# cat /usr/lib64/python2.7/linecache.py 查看源码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值