python - 将文件读取到字符串(python)

标签 python string file

我刚刚将 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()

关于python - 将文件读取到字符串(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42637192/

相关文章:

python - 如何在python中获取azure函数的唯一实例id?

java - Android 上特定情况下格式化日期和时间

algorithm - Firefox 的 'awesome' 栏如何匹配字符串?

PHP - 将 csv 导入数据库数据时间过长

python - 如何在 pandas groupby 中聚合多列

python - 比较数据帧字典中的列

python - 使用 Scikit-learn 确定 RF 模型中每个类的特征重要性

php 使用 preg 自定义解析字符串

file - 如果文件长度相同,哈希冲突的可能性有多大?

java - 在Java中覆盖文本文件的一部分