python - 输出格式不正确

标签 python python-3.7

我正在尝试在 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)

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

如您所见,每行的开头都添加了一个 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')

关于python - 输出格式不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51938771/

相关文章:

python - pip 异常: AttributeError: 'NoneType' object has no attribute 'startswith'

python - ADLS Gen2 上的 Kubernetes Spark-submit 错误 : Class org. apache.hadoop.fs.azurebfs.SecureAzureBlobFileSystem 未找到

python-requests - Python Instagram 使用请求登录

python-2.7 - Python 小数() |小数.InvalidOperation

python - 使用 Python Click,如何添加超过 5 个选项,即超过 5 个?

python - 使用 pandas 滚动对数据帧的所有值进行实际平均值

Python:是否可以有一个类方法作用于类的一部分?

python - DataFrame 中的几何平均值

python - 以 0.05 为增量向上舍入

python - 鸭子类型(duck typing)实践 - Python 3.7