请问Python大神,下面的代码是如何实现指定行输出的?
fromsysimportargvscript,input_file=argvdefprint_all(f):printf.read()defrewind(f):f.se...
from sys import argv
script, input_file = argv
def print_all(f):
print f.read()
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print line_count, f.readline()
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 = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
运行结果:
Now let's rewind, kind of like a tape.
Let's print three lines:
1 To all the people out there.
2 I say I don't like my hair.
3 I need to shave it off.
上述代码是 笨办法学习Python中20节的内容,请问它是如何实现指定行数输出的?本人新手没搞懂啊!
(我使用的Python3,莫非跟版本有关系?) 展开
script, input_file = argv
def print_all(f):
print f.read()
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print line_count, f.readline()
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 = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
运行结果:
Now let's rewind, kind of like a tape.
Let's print three lines:
1 To all the people out there.
2 I say I don't like my hair.
3 I need to shave it off.
上述代码是 笨办法学习Python中20节的内容,请问它是如何实现指定行数输出的?本人新手没搞懂啊!
(我使用的Python3,莫非跟版本有关系?) 展开
展开全部
from sys import argv
script, input_file = argv
def print_all(f):
print f.read()
def rewind(f):
f.seek(0) #把文件指针移动开头
def print_a_line(line_count, f):
print line_count, f.readline() # readline是读取一行
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 = current_line + 1 #这是第二行
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
运行结果:
Now let's rewind, kind of like a tape.
Let's print three lines:
1 To all the people out there.
2 I say I don't like my hair.
3 I need to shave it off.
总结 其实并不是指定行数输出的,只是一行一行输出,然后前面套个行数
你可以这个 for linenumber, line in enumerate(f, start=1):
print(linenumber,':' ,line)更简便
追问
非常感谢,我还是不明白!
readline()函数不指定值得情况下,难道不是应该默认读取第一行吗?
此处readline()为什么会出现第二,第三行? 难道说是缓存或者内存没被释放,就会出现这种使用readline()连续读取同一个文件会自动累加的情况吗?
追答
readline是从文本读取一行, 而不是读取第一行, 是读一行,指针往后移动,再读再移
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询