2015-02-11 121 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)