Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
writing bytes error
#1
When I am writing bytes to a file using this:
string1 = "abc123test"
f = open(filewrite, "wb")
f.write(string1)
f.close()
it gives me this error:
Error:
f.write(string1) TypeError: a bytes-like object is required, not 'str'
can someone help me on this?
Reply
#2
"abc123test" is a unicode string, b"abc123test" would be bytes.
So either change the type of your variable, or change the mode you open the file in.
Reply
#3
I did this:
string1 = 'b"abc123test"'
f = open('file.txt', "wb")
f.write(string1)
f.close()
and it gave the same error
Reply
#4
string1 = b"abc123test"
Reply
#5
thanks!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Error on import: SyntaxError: source code string cannot contain null bytes kirkwilliams2049 7 6,166 Aug-03-2023, 06:00 PM
Last Post: Gribouillis
  how to solve "a bytes-like object is required, not 'str'" error maiya 2 3,729 Jul-28-2020, 07:03 PM
Last Post: bowlofred
  Error When Writing to SQL Table skaailet 1 1,791 Jun-10-2020, 12:01 AM
Last Post: bowlofred
  i am getting error while writing code for exception logging rkgupta51179 1 1,814 Nov-03-2019, 05:12 AM
Last Post: buran
  Getting error "Type error-a bytes-like object..." mrapple2020 1 5,340 Apr-06-2019, 06:37 PM
Last Post: mrapple2020
  replace bytes with other byte or bytes BigOldArt 1 10,527 Feb-02-2019, 11:00 PM
Last Post: snippsat
  Error while writing a code for feature scaling prateek 1 2,483 Aug-15-2017, 09:17 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020