2015-02-11 124 views
1

我目前正在关注“了解Python的难题”。然而,当我使用.read()命令我的.txt文件它输出在一个非常不可思议的方式文本,有额外的空间,并在启动方:在Python中读取txt文件

Extra spaces and squares.

控制台是Windows电源外壳。

我的代码如下所示:

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. 

请帮帮忙!

+0

在这里没有相同的行为(debian linux),必须是你的文件或你的系统的东西。 – 2015-02-11 15:57:36

回答

1

如果你正在使用Python 2.7.x,你应该采取的ASCII字符串做:

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

应该以可读的方式输出文件。正如之前所指出的,该文件似乎是用UTF-16编码的,所以这不应该被视为“读取文本文件的方式”。如果您使用Notepad ++,则可以从“编码”菜单中选择文件编码。 Microsoft记事本允许您在“另存为...”对话框中选择编码。

1

你的文件似乎被编码为2字节编码;据推测UTF-16。由于python无法猜测,它只是输出字节,因为它得到它们;对于纯ASCII文本,这意味着每个其他字符都是纯文本可读的。

0

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

无论您的文件是Unicode,或PowerShell是做一些有趣的事情与编码。上面的链接介绍了如何在Python 2.x中打开Unicode文件 - 相关的部分是在这里:

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