Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a bytes-like object is required, not 'str' JSON File opened as STR

Tags:

I've only learnt the basics of Python please forgive me but I was not able to determine the fix from the other posts. I open my JSON files with 'r' and I think I'm writing to them in r but it doesn't like that. Changing it to 'r' doesn't help :(

For the following section:

if isinstance(to_write, list):     self.log_file.write(''.join(to_write) + "<r/>") else:     self.log_file.write(str(to_write) + "<r/>")     self.log_file.flush() 

The error I get is: a bytes-like object is required, not 'str'

import math import time from random import randint import json  from instagram.client import InstagramAPI  class Bot:     def __init__(self, config_file, tags_file):         # Loading the configuration file, it has the access_token, user_id and others configs         self.config = json.load(config_file)          # Loading the tags file, it will be keep up to date while the script is running         self.tags = json.load(tags_file)          # Log file to output to html the debugging info about the script         self.filename = self.config["path"] + self.config["prefix_name"] + time.strftime("%d%m%Y") + ".html"         self.log_file = open(self.filename, "wb")          # Initializing the Instagram API with our access token         self.api = InstagramAPI(access_token=self.config["access_token"], client_secret=self.config['client_secret'])          # Likes per tag rate         self.likes_per_tag = math.trunc(min(self.config["follows_per_hour"],                                             self.config["likes_per_hour"]) / len(self.tags["tags"]))      def save_tags(self):         j = json.dumps(self.tags, indent=4)         f = open('tags.json', 'w')         print >> f, j         f.close()      def insta_write(self, to_write):         if self.filename != self.config["path"] + self.config["prefix_name"] + time.strftime("%d%m%Y") + ".html":             self.log_file.close()             self.filename = self.config["path"] + self.config["prefix_name"] + time.strftime("%d%m%Y") + ".html"             self.log_file = open(self.filename, "wb")          if isinstance(to_write, list):             self.log_file.write(''.join(to_write) + "<r/>")         else:             self.log_file.write(str(to_write) + "<r/>")             self.log_file.flush()      def going_sleep(self, timer):         sleep = randint(timer, 2 * timer)         self.insta_write("SLEEP " + str(sleep))         time.sleep(sleep)      def like_and_follow(self, media, likes_for_this_tag):         try:             var = self.api.user_relationship(user_id=media.user.id)              if self.config["my_user_id"] != media.user.id:                 self.insta_write("--------------")                 self.insta_write(var)                  if var.outgoing_status == 'none':                     self.insta_write("LIKE RESULT:")                     self.insta_write(self.api.like_media(media_id=media.id))                      self.insta_write("FOLLOW RESULT:")                     self.insta_write(self.api.follow_user(user_id=media.user.id))                      likes_for_this_tag -= 1                      self.going_sleep(self.config["sleep_timer"])                 else:                     self.going_sleep(self.config["sleep_timer"] / 2)          except Exception as e:             self.insta_write(str(e))             self.insta_write("GOING SLEEP 30 min")             time.sleep(1800)             self.like_and_follow(media, likes_for_this_tag)          return likes_for_this_tag      def run(self):         while True:             for tag in self.tags["tags"].keys():                 tag = str(tag)                  self.insta_write("--------------------")                 self.insta_write("TAG: " + tag)                 self.insta_write("--------------------")                  self.insta_write("--------------------")                 self.insta_write("DICTIONARY STATUS:")                  for keys, values in self.tags["tags"].items():                     self.insta_write(keys)                     if values is not None:                         self.insta_write(values)                  likes_for_this_tag = self.likes_per_tag                  while likes_for_this_tag > 0 and self.tags["tags"][tag] != 0:                     if self.tags["tags"][tag] is None:                         media_tag, self.tags["tags"][tag] = self.api.tag_recent_media(tag_name=tag,                                                                                       count=likes_for_this_tag)                     else:                         media_tag, self.tags["tags"][tag] = self.api.tag_recent_media(tag_name=tag,                                                                                       count=likes_for_this_tag,                                                                                       max_tag_id=self.tags["tags"][tag])                      self.insta_write("API CALL DONE")                      if len(media_tag) == 0 or self.tags["tags"][tag] is None:                         self.tags["tags"][tag] = 0                         likes_for_this_tag = 0                     else:                         self.insta_write(self.tags["tags"][tag])                         self.tags["tags"][tag] = self.tags["tags"][tag].split("&")[-1:][0].split("=")[1]                      self.save_tags()                      for m in media_tag:                         likes_for_this_tag = self.like_and_follow(m, likes_for_this_tag)                  if reduce(lambda r, h: r and h[1] == 0, self.tags["tags"].items(), True):                     self.insta_write("END")                     exit(1)    if __name__ == '__main__':     bot = Bot(open("config_bot.json", "r"), open("tags.json", "r"))     bot.run() 
like image 337
Jack Jack Henry Avatar asked Nov 22 '15 21:11

Jack Jack Henry


People also ask

How do you fix a bytes like an object is required not str?

Typeerror a bytes like object is required not str error occurs when we compare any 'str' object with the 'byte' type object. The best way to fix this error is to convert them into 'str' before comparison or any other operation.

How do you define a byte like object in Python?

Bytes-like object in python In Python, a string object is a series of characters that make a string. In the same manner, a byte object is a sequence of bits/bytes that represent data. Strings are human-readable while bytes are computer-readable. Data is converted into byte form before it is stored on a computer.

How do you make a byte like an object?

Bytes-Like Object Similar Error You may encounter this error if you try to use a string method on a list of bytes. To solve this error, you can use the same approach that we used to solve the last error. Make sure that you open up any text files in text read mode instead of binary read mode.

What is the difference between JSON dump and JSON dumps?

json. dump() method used to write Python serialized object as JSON formatted data into a file. json. dumps() method is used to encodes any Python object into JSON formatted String.


1 Answers

You opened the file as binary:

self.log_file = open(self.filename, "wb") 

but are writing str Unicode strings to it. Either open the file in text mode (with an encoding set) or encode each string, separately.

Opening the file in text mode is easiest:

self.log_file = open(self.filename, "w", encoding="utf8") 
like image 71
Martijn Pieters Avatar answered Nov 23 '22 22:11

Martijn Pieters