Python readlines() usage and efficient practice for reading

The short version is: The efficient way to use readlines() is to not use it. Ever. I read some doc notes on readlines(), where people has claimed that this readlines() reads whole file content into memory and hence generally consumes more memory compared to readline() or read(). The documentation for readlines() explicitly guarantees that it … Read more

How to extract top-level domain name (TLD) from URL

Here’s a great python module someone wrote to solve this problem after seeing this question: https://github.com/john-kurkowski/tldextract The module looks up TLDs in the Public Suffix List, mantained by Mozilla volunteers Quote: tldextract on the other hand knows what all gTLDs [Generic Top-Level Domains] and ccTLDs [Country Code Top-Level Domains] look like by looking up the … Read more

How to convert a decimal number into fraction?

You have two options: Use float.as_integer_ratio(): >>> (0.25).as_integer_ratio() (1, 4) (as of Python 3.6, you can do the same with a decimal.Decimal() object.) Use the fractions.Fraction() type: >>> from fractions import Fraction >>> Fraction(0.25) Fraction(1, 4) The latter has a very helpful str() conversion: >>> str(Fraction(0.25)) ‘1/4’ >>> print Fraction(0.25) 1/4 Because floating point values … Read more

scipy: savefig without frames, axes, only content

EDIT Changed aspect=”normal to aspect=”auto’ since that changed in more recent versions of matplotlib (thanks to @Luke19). Assuming : import matplotlib.pyplot as plt To make a figure without the frame : fig = plt.figure(frameon=False) fig.set_size_inches(w,h) To make the content fill the whole figure ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) Then draw your … Read more