Reputation: 43
I am working with python 3 and have a text file which I put in a string variable and then create an byte array like this:
file = open('labb9Text.txt', "r")
for lines in file:
txt = str(lines)
byteArr = bytearray(txt, 'utf-8')
Now I want to retrieve that variable outside the for loop. I have tried doing like this:
byteArr = bytearray()
file = open('labb9Text.txt', "r")
for lines in file:
txt = str(lines)
byteArr = bytearray(txt, 'utf-8')
print(byteArr)
But this does not work, the byteArr is empty. How can I do this?
Thanks in advance
Upvotes: 0
Views: 721
Reputation: 22478
It works correctly, but only in a very literal sense. Why is byteArr
empty after running that loop? Because inside the loop, you are setting it to the contents of every single line in turn, and the very last line must be empty. So you get a valid result for your last line only.
You correctly create a variable byteArr
before the loop, but inside the loop you must add the new bytes, not replace them.
A few more notes: in lines in file..
the variable lines
is already a string, so txt = str(lines)
is not necessary. It's generally neater to use with
to open a file, because it also automatically closes it at the end of that code block (and indeed it's something you forgot to do here).
byteArr = bytearray()
with open('labb9Text.txt', "r") as file:
for lines in file:
byteArr += bytearray(lines, 'utf-8')
print (byteArr)
As things go, this can even be done much easier, but only if that encoding utf-8
is not really necessary (that is, if the file already is in the correct encoding):
with open('labb9Text.txt', "rb") as file:
byteArray = bytearray(file.read())
It doesn't need any loop at all.
Upvotes: 1