Categories
Python Answers

How to pretty print a JSON file with Python?

Sometimes, we want to pretty print a JSON file with Python.

In this article, we’ll look at how to pretty print a JSON file with Python.

How to pretty print a JSON file with Python?

To pretty print a JSON file with Python, we can use the json.dumps method with the indent and sort_keys parameters.

For instance, we write:

import json

your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
parsed = json.loads(your_json)
print(json.dumps(parsed, indent=2, sort_keys=True))

We call json.loads with your_json to load the JSON string into a dictionary.

Then we call json_dumps with the parsed JSON and indent set to 2 to indent each level with 2 spaces.

sort_keys is set to True to sort the keys alphabetically.

Therefore,

[
  "foo",
  {
    "bar": [
      "baz",
      null,
      1.0,
      2
    ]
  }
]

is printed.

Conclusion

To pretty print a JSON file with Python, we can use the json.dumps method with the indent and sort_keys parameters.

Categories
Python Answers

How to profile a Python script?

Sometimes, we want to profile a Python script.

In this article, we’ll look at how to profile a Python script.

How to profile a Python script?’

To profile a Python script, we can use the cProfile.run method.

For instance, we write:

import cProfile


def hello():
    print('hello')


cProfile.run('hello()')

We put the code into the string that we call cProfile.run with to profile the hello function’s execution.

Then we get output like:

         5 function calls in 0.000 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 main.py:4(hello)
        1    0.000    0.000    0.000    0.000 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {built-in method builtins.print}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

printed on the screen.

Conclusion

To profile a Python script, we can use the cProfile.run method.

Categories
Python Answers

How to import a module given the full path in Python?

Sometimes, we want to import a module given the full path in Python.

In this article, we’ll look at how to import a module given the full path in Python.

How to import a module given the full path in Python?

To import a module given the full path in Python, we can use the importlib.util module.

For instance, if we have the following module:

foo.py:

def hello():
    print('hello')

Then if main.py is in the same folder and we want to use foo.py in it.

We write:

import importlib.util

spec = importlib.util.spec_from_file_location("module.name", "./foo.py")
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.hello()

We call importlib.util.spec_from_file_location with 'module.name' and './foo.py‘ to import the module.

Then we call importlib.util.module_from_spec to import the returned spec object.

Next, we call spec.loader.exec_module with the imported foo module to load it.

And then we call foo.hello to run the hello function in foo.py.

Therefore, 'hello' should be printed.

Conclusion

To import a module given the full path in Python, we can use the importlib.util module.

Categories
Python Answers

How to convert an integer to string in Python?

Sometimes, we want to convert an integer to string in Python.

In this article, we’ll look at how to convert an integer to string in Python.

How to convert an integer to string in Python?

To convert an integer to string in Python, we can use the str function.

For instance, we write:

num =  str(10)
print(num)

We call str with the number we want to convert to a string.

And the string version of the number is returned.

Then num is '10'.

Conclusion

To convert an integer to string in Python, we can use the str function.

Categories
Python Answers

How to reverse a string in Python?

Sometimes, we want to reverse a string in Python.

In this article, we’ll look at how to reverse a string in Python.

How to reverse a string in Python?

To reverse a string in Python, we can put [::-1] after the string.

For instance, we write:

rev = 'hello world'[::-1]
print(rev)

We use -1 with no start and end indexes to reverse the string.

Therefore, rev is 'dlrow olleh'.

Conclusion

To reverse a string in Python, we can put [::-1] after the string.