我是Python和编码的新手,我一直在努力通过Learn Python The Hard Way,刚刚完成了ex20,我完成了所有事情并且非常确定我理解了这一切,但出于某种原因,当我运行以下脚本时,我不这样做在结尾的行的开头得到数字1,2和3,但我没有得到任何错误。
这是我的代码:
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 # a blank line
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 += 1
print_a_line(current_line, current_file)
这就是您应该看到的内容:
$ python ex20.py test.txt
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中获得的
PS C:\Users\David\lpthw> python ex20.py test.txt
First let's print the whole file:
■t h i s i s a l i n e 1
t h i s i s a l i n e 2
t h i s i s a l i n e 3
Now let's rewind, kind of like a tape.
Let's print three lines:
■t h i s i s a l i n e 1
t h i s i s a l i n e 2
t h i s i s a l i n e 3
我一直在逐行扫描我的代码并且无法理解为什么我在最后3行的开头没有得到数字,也不知道为什么我在开始时有这些数据
答案 0 :(得分:0)
如果您使用Notepad ++,我遇到了同样的问题。我尝试切换到记事本,当我以UTF-8保存时几乎解决了问题。最后,我尝试将其保存在ANSI编码中,结果非常完美。对于Notepad ++,当您编写文本文件时,只需转到顶部菜单栏并确保选择ANSI。