学习python艰难的方式练习20行号码

时间:2014-12-15 21:43:21

标签: python function

执行Exercise 20 (Functions and Files) of Learn Python the Hard Way,这是我的代码:

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)

运行时应该是这样的:

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

但问题是倒带后没有行号,就像:

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:
      This is line 1

     This is line 2

     This is line 3

在第一个“This”之前有一个空格,并且之前还有一个黑色矩形:

http://oi59.tinypic.com/x659s.jpg

我无法弄清问题是什么,如果有人可以提供帮助,我会很高兴。

1 个答案:

答案 0 :(得分:3)

您所看到的是解释“utf16le'中的文字的结果”。 as' ascii',并将其打印到Windows控制台。您可以通过两种方式解决此问题。 Notepad ++称之为“UCS-2小端”'。

选项1:,在Notepad ++中,选择" ANSI"从编码菜单中再次保存文本文件(包含"这是第1行"等等)的文件。问题应该消失。

选项2:让您的程序识别unicode,交换:

current_file = open(input_file)

import codecs
current_file = codecs.open(input_file, 'r', 'utf-16-le')

由于您正在尝试学习python(艰难的方式),我推荐选项1,但您最终必须在程序中接受unicode感知。