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

python histogram one-liner [duplicate]

Python 3.x does have reduce, you just have to do a from functools import reduce. It also has “dict comprehensions”, which have exactly the syntax in your example. Python 2.7 and 3.x also have a Counter class which does exactly what you want: from collections import Counter cnt = Counter(“abracadabra”) In Python 2.6 or earlier, … Read more

Simple example of how to use ast.NodeVisitor?

ast.visit — unless you override it in a subclass, of course — when called to visit an ast.Node of class foo, calls self.visit_foo if that method exists, otherwise self.generic_visit. The latter, again in its implementation in class ast itself, just calls self.visit on every child node (and performs no other action). So, consider, for example: … Read more

How do I get Python’s ElementTree to pretty print to an XML file?

Whatever your XML string is, you can write it to the file of your choice by opening a file for writing and writing the string to the file. from xml.dom import minidom xmlstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent=” “) with open(“New_Database.xml”, “w”) as f: f.write(xmlstr) There is one possible complication, especially in Python 2, which is both less … Read more