Python 3.6 - Reading encoded text from a file and converting to a string

Hope someone can help me with the following. It may not be too difficult, but I could not figure it out. My file "output.txt" is created with:

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

If I do not encode it to write to a file, this will give me errors. Thus, the "output" contains 3 lines of output encoded with utf-8:

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

In "main.py", I am trying to convert this back to a string:

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

Unfortunately, b '' format has not been deleted yet. Should I still decode it? If possible, I would like to keep the structure of 3 lines. My apologies for the newbies question, this is my first on SO :)

Thank you so much in advance!

+4
3

b ' , , . -, , write(print(line)) write(line). , , literal_eval. @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
0

.

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

With the help of the people who answer my question, I was able to get it to work. The solution is to change the way you write to the file:

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

Then read this as:

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

Source: https://habr.com/ru/post/1671639/


All Articles