Zed Shaw运动20不起作用

时间:2014-12-15 10:32:13

标签: python windows python-2.7 for-loop printing

当我在下面键入时:

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)

它没有在我的PowerShell中打印或工作它应该打印出来:

First let’s print the whole file:
This is line 1
This is line 2
This is line 3
Now let’s rewind, kind of like a tape.
Let’s print three lines:
1 This is line 1
2 This is line 2
3 This is line 3
在powershell中输入

$ python ex20.py test.txt

1 个答案:

答案 0 :(得分:0)

你不是调用任何东西。您的脚本定义了函数,但从未实际使用过任何函数。

这是因为应该调用函数的所有行都缩进为print_a_line()函数的一部分。取消缩进以将它们移动到模块级别,以便在脚本运行时执行它们:

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)