python指定位置写入文件_Python 将字符串写入文本文件中指定位置和删除行示例代码...

1、写入文本文件中指定位置def update(filename, lineno, column, text):

fro = open(filename, "rb")

current_line = 0

while current_line < lineno - 1:

fro.readline()

current_line += 1

seekpoint = fro.tell()

frw = open(filename, "r+b")

frw.seek(seekpoint, 0)

# read the line we want to update

line = fro.readline()

chars = line[0: column-1] + text + line[column-1:]

while chars:

frw.writelines(chars)

chars = fro.readline()

fro.close()

frw.truncate()

frw.close()

if __name__ == "__main__":

update("file.txt", 4, 13, "History ")

2、删除文本文件中指定行def removeLine(filename, lineno):

fro = open(filename, "rb")

current_line = 0

while current_line < lineno:

fro.readline()

current_line += 1

seekpoint = fro.tell()

frw = open(filename, "r+b")

frw.seek(seekpoint, 0)

# read the line we want to discard

fro.readline()

# now move the rest of the lines in the file

# one line back

chars = fro.readline()

while chars:

frw.writelines(chars)

chars = fro.readline()

fro.close()

frw.truncate()

frw.close()

相关文档:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值