Python学习笔记(笨方法学Python3)-习题20:函数和文件

from sys import argv

srcipt, input_file = argv

def print_all(fp):
    print(fp.read())

def print_oneline(line_count,fp):
    print(line_count, fp.readline(), end = "")

def rewind(fp):
    fp.seek(0)

fp=open(input_file)

print("Let's print the whole file:")
print_all(fp)

print("now let's rewind, kind of like a tape.")
rewind(fp)

print("Let's print three lines:")
count=1
print_oneline(count, fp)
count += 1
print_oneline(count, fp)
count += 1
print_oneline(count, fp)

print("")

结果为:
在这里插入图片描述
*seek()函数处理的是字节而非行,seek(0)只是转到文件的0字节位置
*readline()会扫描文件的每一个字节,直到找到一个‘\n’为止
*文件会记录每次调用readline()后的读取位置
*readline()返回的内容有‘\n’,因此要在print中加入一个参数: end=""

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值