How do I write JSON data to a file?

data is a Python dictionary. It needs to be encoded as JSON before writing. Use this for maximum compatibility (Python 2 and 3): import json with open(‘data.json’, ‘w’) as f: json.dump(data, f) On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file using: import json with open(‘data.json’, ‘w’, encoding=’utf-8′) … Read more

Save plot to image file instead of displaying it using Matplotlib

When using matplotlib.pyplot.savefig, the file format can be specified by the extension: from matplotlib import pyplot as plt plt.savefig(‘foo.png’) plt.savefig(‘foo.pdf’) That gives a rasterized or vectorized output respectively. In addition, there is sometimes undesirable whitespace around the image, which can be removed with: plt.savefig(‘foo.png’, bbox_inches=”tight”) Note that if showing the plot, plt.show() should follow plt.savefig(); … Read more

Reverse a string in Python

Using slicing: >>> ‘hello world'[::-1] ‘dlrow olleh’ Slice notation takes the form [start:stop:step]. In this case, we omit the start and stop positions since we want the whole string. We also use step = -1, which means, “repeatedly step from right to left by 1 character”.

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)