Skip to main content
 首页 » 编程设计

python之输出格式不正确

2025年05月04日10birdshome

我正在尝试在 PowerShell 中运行我正在阅读的一本书中的一些代码以学习 Python(3.7),但我的输出与预期不符,我看不出哪里出错了。

这是代码:

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) 

输出的格式似乎是出了问题的地方。

如您所见,每行的开头都添加了一个 y,在应该打印 1 行的部分,它跳过了第二行。

文件 test.txt 包含:

this is line 1 
this is line 2 
this is line 3 

附言。我知道有更有效的方法来执行其中一些操作,但这不是这里的重点。

请您参考如下方法:

文件的前两个字节是 0xFF 和 0xFE。这是 "byte order mark"这表明文件的编码是 Unicode 16 位小端。看一下 the table in the wikipedia page 中的第三行;它显示了与您在输出中看到的相同的两个字符 ÿþ。

要读取文件,请在 open 调用中提供参数 encoding='UTF-16':

current_file = open(input_file, encoding='UTF-16')