读取 python 中的 txt 文件

Reading txt files in python

我目前正在关注 "Learn Python the Hard Way"。但是,当我在我的 .txt 文件上使用 .read() 命令时,它以一种非常奇怪的方式输出文本,带有额外的空格,并且在开头有一个正方形:

控制台是 Windows Powershell。

我的代码如下所示:

from sys import argv #imports argv from sys

script, filename = argv #unpacks script and filename from argv

txt = open(filename) #declares the variable txt as the text in filename

print "Here's your file %r" % filename #prints the string and the filename
print txt.read() #prints a reading of txt
txt.close()

print "Type the filename again:" #prints the string
file_again = raw_input("> ") #declares the variable file_again as the raw input

txt_again = open(file_again) #declares the variable txt_again as the text in file_again

print txt_again.read() #prints a reading of txt_again
txt.close()

文件如下所示:

This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.

请帮忙!

您的文件似乎使用 2 字节编码;大概是UTF-16。由于 python 无法猜测,它只是在获取字节时输出字节;对于纯 ASCII 文本,这意味着每个其他字符都是纯文本可读的。

看看https://docs.python.org/2/howto/unicode.html

要么您的文件是 Unicode,要么 PowerShell 对编码做了一些有趣的事情。上面的 link 解释了如何在 Python 2.x 中打开 Unicode 文件 - 相关部分在这里:

import codecs
f = codecs.open('unicode.rst', encoding='utf-8')
for line in f:
  print repr(line)

如果您正在使用 Python 2.7.x,您应该使用该 ASCII 字符串并执行:

text = txt.read().decode("utf-16")
print text

这应该以可读的方式输出文件。正如之前指出的那样,该文件似乎是用 UTF-16 编码的,因此不应将其视为 "the way to read text files"。如果您使用 Notepad++,您可以从 "Encoding" 菜单中 select 文件编码。 Microsoft 记事本允许您 select 在 "Save as..." 对话框中进行编码。