【发布时间】:2018-05-31 22:01:56
【问题描述】:
我编写了以下 Python 3 脚本:
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print(f"Copying from {from_file} to {to_file}")
in_file = open(from_file)
indata = in_file.read()
print(f"The input file is {len(indata)} bytes long")
print(f"Does the output file exist? {exists(to_file)}")
print("Ready, hit RETURN to continue, CTRL-C to abort.")
input()
out_file = open(to_file, 'w')
out_file.write(indata)
print("Alright, all done.")
out_file.close()
in_file.close()
显然len(indata) 的输出应该是:
The input file is 21 bytes long
但我明白了:
The input file is 46 bytes long
from_file 是一个名为 test.txt 的文件,其中包含文本“这是一个测试文件”。
我仔细检查了 test.txt 中的文本。我认为差异可能在计算机上,因为我使用的是 Windows 而老师没有。
Expected output of the exercise according to Zed
这是我在这里的第一篇文章,我已经尝试找到有关此问题的信息。虽然我发现了关于练习 17 的一些问题,但我没有发现字节差异。
【问题讨论】:
-
您的文件可能包含空格。哦,是的:您使用的是哪个 Python 版本?
-
Windows 和我的 Ubuntu VM 都确认这应该是 20 字节长。书中可能有勘误。
-
Ups,谢谢,@brunodesthuilliers,超级新手的错误。 Python 3,我将编辑问题。
-
我看到@Mangohero1。您的输出最接近“正确的”。感谢您的检查。
-
这看起来很像“这是一个测试文件”的 utf-16 编码表示 - 除了 BOM(应该是
"\xff\xfe",而不是“ÿþ”)。您必须了解字符串/字节字符串/unicode 字符串等在 Python2 和 Python3 中是完全不同的野兽。您是如何生成测试文件的?
标签: python python-3.x