笨办法学python习题20 函数和文件

本文通过一个实战案例,详细介绍了Python中文件的基本操作方法,包括如何使用脚本接收命令行参数、打开文件、读取文件内容、重置文件指针及逐行读取等关键步骤。

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

习题20是文件和函数结合的联系题。这这个练习题中,我们可以学习到以下几个知识点:

1,复习脚本从terminal中接受参数的用法

2,文件的open函数和read方法复习

3,文件的seek方法

4,文件的readline方法

5,+=操作符的用法

代码如下:

#-*-coding:utf-8-*-
#知识点1:从sys库中导入argv模块
from sys import argv
#将从terminal中接受的2个参数解包后赋值给变量
script, input_file = argv
#定义打印所有内容的函数
def print_all(f):
	print f.read() #知识点2:f为fileobject对象,所以下方必须要有open函数
#定义重定位函数	
def rewind(f):     
	f.seek(0)      #知识点3:指针的重定位,f为fileobject
#定义打印一行函数	
def print_a_line(line_count,f):
	print line_count, f.readline()#知识点4
#知识点2:open函数打开input_file文件,给函数中的read()/seek()方法做准备
current_file = open(input_file)

print"First let's print the whole file:\n"

print_all(current_file)

print"Now let's rewind, kind of like a tape."

rewind(current_file)

print"Let‘s print three lines:"

current_line = 1
print_a_line(current_line, current_file)

current_line += 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line,current_file)
3,特别说明seek()方法的语法:

fileobject.seek(offset[,whence])

①offset----开始的偏移量,也就是代表要移动偏移的自己数

②whence----可选,默认值为0.给offset参数一个定义,表示要从哪一个文职开始偏移,0代表从文件中开头算起。1代表从当前位置开始,2代表从文件末尾算起

4,current_line = current_line + 1的另外一种写法 current += 1

其余的知识点见代码的注释部分。

运行结果如下:

simengred$ python ex20.py test.txt
First let's print the whole file:

iloveyou
Did you love me
I don't know

Now let's rewind, kind of like a tape.
Let‘s print three lines:
1 iloveyou

2 Did you love me

3 I don't know




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值