Skip to main content
 首页 » 编程设计

python之将文件读入字符串(python)

2024年10月01日28myhome

我刚刚将 Anaconda 安装到 Windows 10 机器上(Python 2.7.12 |Anaconda 4.2.0(64 位)|) 我在从文件中读取文本时遇到问题。 请参阅下面的代码和输出。我想要文件中的实际文本。

谢谢!!

输出:

 ['\xff\xfeT\x00h\x00i\x00s\x00', 
  '\x00i\x00s\x00', 
   '\x00a\x00', 
   '\x00t\x00e\x00s\x00t\x00.\x00', 
   '\x00', 
   '\x00', 
   '\x00', 
   '\x00T\x00h\x00i\x00s\x00', 
   '\x00i\x00s\x00', 
   '\x00a\x00', 
   '\x00t\x00e\x00s\x00t\x00'] 

代码:

try:     
    with open('test.txt', 'r') as f:         
        text = f.read() 
except Exception as e: 
    print e 
    print text.split() 

测试.txt:

This is a test. 
 
This is a test 

请您参考如下方法:

我非常幸运地使用 io 模块打开带有显式编码的文件。

import io 
with io.open(FILE, 'r', encoding='utf-16') as f: 
    job = f.read()