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

Python 3.6-从文件中读取编码文本并转换为字符串,python,python-3.x,encoding,decoding,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() 如果我不将其编码以写入文件,它将给我错误。

希望有人能在以下方面帮助我。这可能不太复杂,但我还没弄明白。我的“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行结构。 我为这个新手问题道歉,这是我第一次问这样的问题:)


提前非常感谢

不要在打开文件时指定编码,而是在读取时使用它进行解码

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

如果
b
和引号
在您的文件中,这意味着您的文件存在问题。可能有人写(打印(行))而不是写(行)。现在要解码它,你可以使用。否则@m_callens的答案应该可以

import ast

with open("b.txt", "r") as f:
    text = [ast.literal_eval(line) for line in f]

for l in text: 
    print(l.decode('utf-8'))

# testtesttest
# line2test
# ʃɔn keɪn

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

     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()

呃,文件中是否有
b'testtest'
?如果文件中有
b
'
,您可以使用
f.write
而不是
print
?@MaxChrétien,这似乎有效!:)谢谢大家!
f=open('output.txt','wb')
尝试添加
b
然后,它将允许您将
字节
写入文件,而不是
str
这将导致以下错误:AttributeError:'str'对象没有属性'decode'@Hoenie获取字节字符串的唯一方法(
b'abc'
)是通过打开文件以二进制形式读取,如果你没有从文件中读取字节,你怎么会得到bytestring?rb和解码实际上给了我相同的输出“r”,没有解码实际上,我自己把它写到文件中。我将其编码为utf-8作为文本文件,否则我会得到一个错误,这是来自Twitter流。打印是用以下代码完成的:打印(tweet['text'].encode('utf-8'):)请编辑您的问题,因为您首先是如何创建文件的。还有,你试过我的代码了吗?明白了,我编辑了我的问题。我尝试了你的代码,但输出保持不变。谢谢你的反馈!编辑我的问题,很抱歉我之前没有尝试使用python 3.X。。。现在应该可以工作了,但我正在做一些更好的事情。如果你的评论“write(print(line))而不是write(line)”,我会重写我的代码。谢谢!