Extract file name from path, no matter what the os/path format

There’s a function that returns exactly what you want import os print(os.path.basename(your_path)) WARNING: When os.path.basename() is used on a POSIX system to get the base name from a Windows-styled path (e.g. “C:\\my\\file.txt”), the entire path will be returned. Example below from interactive python shell running on a Linux host: Python 3.8.2 (default, Mar 13 2020, … Read more

How to overcome “datetime.datetime not JSON serializable”?

My quick & dirty JSON dump that eats dates and everything: json.dumps(my_dictionary, indent=4, sort_keys=True, default=str) default is a function applied to objects that aren’t serializable. In this case it’s str, so it just converts everything it doesn’t know to strings. Which is great for serialization but not so great when deserializing (hence the “quick & … Read more

How do I trim whitespace?

For whitespace on both sides, use str.strip: s = ” \t a string example\t ” s = s.strip() For whitespace on the right side, use str.rstrip: s = s.rstrip() For whitespace on the left side, use str.lstrip: s = s.lstrip() You can provide an argument to strip arbitrary characters to any of these functions, like … Read more