Home > Software design >  'utf-8' codec can't decode byte 0xa0 in position 0: invalid start byte django
'utf-8' codec can't decode byte 0xa0 in position 0: invalid start byte django

Time:09-05

so i have variable contains in bytes and i want to save it to str. but how to do it? i tried various kinds of ways, but always got error

'utf-8' codec can't decode byte 0xa0 in position 0: invalid start byte

i want to save the result encrypt file to text file. so i have the proof it the file was encrypt. here;s my ways 1:

 def create_file(f):
     response = HttpResponse(content_type="text/plain")
     response['Content-Disposition'] = 'attachment; filename=file.txt'

     filename = f
     print(filename)
     name_byte = codecs.decode(filename)
     print(name_byte)

     return response

my ways 2 :

def create_file(enc):
    with open("file.txt", "w", encoding="utf-8") as f:
        enc = enc.decode('utf-8')
        f.write(enc)

my ways 3:

def create_file(f):
    file = open("file.txt", "w")
    f = f.decode('utf-8')
    download = file.write(f)
    file.close()
    print(download)

    return download

f = b'\xa0\x0e\xdc\x14' f is the return result of encrypt

i called the function :

#in views
download = create_file(enc)
           print(download)

#in urls
path("create_file", views.create_file, name="create_file"),

#in html
<a href="{% url 'create_file' %}">

CodePudding user response:

The phrase "have variable contains in bytes and i want to save it to str" makes no sense at all. bytes and str are different data types serving different purposes. bytes holds a byte stream while str hold abstract text. Yes, bytes can also hold textual info encoded in some text encoding like UTF-8, but that is only a specific case. If, for example, your bytes hold a JPEG image then converting it to str does not make any sense simply because it's not text. So if your encrypted file contains a byte stream you need to treat it as such. It's not text any more until you decrypt it.

So the only thing you can do is to save your byte stream as is using the binary file mode:

v = b'\xa0\x0e\xdc\x14'
with open ('/path', 'wb') as fo:
    fo.write(v)

The same applies to sending the encrypted file as Django response:

response = HttpResponse(v, content_type="application/octet-stream")
response['Content-Disposition'] = 'attachment; filename=file.bin'

CodePudding user response:

If you just want to write the entire line to file then all you have to do is convert to string.

So this would work:

v = b'\xa0\x0e\xdc\x14'

with open("C:/test/output.txt", 'w') as file:
    file.write(str(v))

The result is a text file like this:

enter image description here

  • Related