Python 3.6 - 从文件中读取编码文本并转换为字符串

标签 python python-3.x encoding decoding python-3.6

希望有人能帮我解决以下问题。它可能并不太复杂,但我一直无法弄清楚。我的“output.txt”文件是用以下内容创建的:

f = open('output.txt', 'w')
print(tweet['text'].encode('utf-8'))
print(tweet['created_at'][0:19].encode('utf-8'))
print(tweet['user']['name'].encode('utf-8')) 
f.close()

如果我不对它进行编码以写入文件,它会给我错误。所以“输出”包含 3 行 utf-8 编码输出:

b'testtesttest'
b'line2test'
b'\xca\x83\xc9\x94n ke\xc9\xaan'

在“main.py”中,我试图将其转换回字符串:

f = open("output.txt", "r", encoding="utf-8")
text = f.read()
print(text)
f.close()

遗憾的是,b'' - 格式仍未删除。我还需要解码吗?如果可能的话,我想保留 3 行结构。 对于新手问题,我深表歉意,这是我在 SO 上的第一个问题 :)

提前致谢!

最佳答案

在回答我问题的人们的帮助下,我已经能够让它发挥作用。解决方案是更改写入文件的方式:

     tweet = json.loads(data)
     tweet_text = tweet['text'] #  content of the tweet
     tweet_created_at = tweet['created_at'][0:19] #  tweet created at
     tweet_user = tweet['user']['name']  # tweet created by
     with open('output.txt', 'w', encoding='utf-8') as f:
           f.write(tweet_text + '\n')
           f.write(tweet_created_at+ '\n')
           f.write(tweet_user+ '\n')

然后像这样阅读:

    f = open("output.txt", "r", encoding='utf-8')
    tweettext = f.read()
    print(text)
    f.close()

关于Python 3.6 - 从文件中读取编码文本并转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42635244/

相关文章:

django - 使用 xlswriter || 自动调整列宽 Django

java - 如何从 PrintStream 字节编码中恢复?

ruby - 猜测日志文件中字节流的字符串编码

javascript - nodejs - request.get(url) 在 yahoo.com 的情况下返回二进制数据

python - Pytorch - 在 softmax 层之后选择最佳概率

javascript - 如何在 Python 中正确粘贴有效的 JS 代码作为字符串,跳过所有可能的字符并且不插入任何内容?

python - 使用 BeautifulSoup CSS 选择器获取文本

Python "in"range() 上的运算符时间复杂度

python - 构建 DeBruijn 图的算法给出了错误的结果

python - 遍历字典并按顺序打印其值