“TypeError: a bytes-like object is required, not ‘str'” when handling file content in Python 3

You opened the file in binary mode: with open(fname, ‘rb’) as f: This means that all data read from the file is returned as bytes objects, not str. You cannot then use a string in a containment test: if ‘some-pattern’ in tmp: continue You’d have to use a bytes object to test against tmp instead: … Read more

“TypeError: method() takes 1 positional argument but 2 were given” but I did only pass one

In Python, this: my_object.method(“foo”) …is syntactic sugar, which the interpreter translates behind the scenes into: MyClass.method(my_object, “foo”) …which, as you can see, does indeed have two arguments – it’s just that the first one is implicit, from the point of view of the caller. This is because most methods do some work with the object … Read more

How can I safely create a directory (possibly including intermediate directories)?

On Python ≥ 3.5, use pathlib.Path.mkdir: from pathlib import Path Path(“/my/directory”).mkdir(parents=True, exist_ok=True) For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it: Try os.path.exists, and consider os.makedirs for the creation. import os if not os.path.exists(directory): os.makedirs(directory) As noted in comments … Read more

Why doesn’t calling a string method (such as .replace or .strip) modify (mutate) the string?

This is because strings are immutable in Python. Which means that X.replace(“hello”,”goodbye”) returns a copy of X with replacements made. Because of that you need replace this line: X.replace(“hello”, “goodbye”) with this line: X = X.replace(“hello”, “goodbye”) More broadly, this is true for all Python string methods that change a string’s content “in-place”, e.g. replace,strip,translate,lower/upper,join,… … Read more

Upgrading pip fails with syntax error caused by sys.stderr.write(f”ERROR: {exc}”)

You can get an older version (2.7) of get-pip.py curl https://bootstrap.pypa.io/pip/2.7/get-pip.py –output get-pip.py In my opinion, you should create a python2 virtualenv and install your python2 package in it, as well as pip2. For example, when I installed cuckoo sandbox, I did it like this: virtualenv –python=python2 cuckoo/ # make your virtualenv folder with python2 … Read more

How to create a Python dictionary with double quotes as default quote format?

json.dumps() is what you want here, if you use print(json.dumps(pairs)) you will get your expected output: >>> pairs = {‘arun’: ‘maya’, ‘bill’: ‘samantha’, ‘jack’: ‘ilena’, ‘hari’: ‘aradhana’} >>> print(pairs) {‘arun’: ‘maya’, ‘bill’: ‘samantha’, ‘jack’: ‘ilena’, ‘hari’: ‘aradhana’} >>> import json >>> print(json.dumps(pairs)) {“arun”: “maya”, “bill”: “samantha”, “jack”: “ilena”, “hari”: “aradhana”}