Using Python’s print With No Newline

Maybe I’m the only one who didn’t know that, but yesterday I learned how to make Python’s print function not write \n.

If you’re using Python’s print function to write stuff to standard output, you’re probably used to its default behavior of ending lines with \n:

> for i in xrange(5): print i
0
1
2
3
4

Sometimes you don’t want it to add the trailing newline. I used to think that in such cases, I need to switch to sys.stdout:

> import sys
> %paste
for i in xrange(5):
    sys.stdout.write('%d ' % (i))
else:
    sys.stdout.write('\n')  # for the trailing newline after the last iteration

## -- End pasted text --
0 1 2 3 4

Turns out that the print function supports the same behavior with a trailing comma!

> for i in xrange(5): print i,

0 1 2 3 4

Of course, this is covered in the documentation.

Every day I learn something new…

Manipulating Python os.walk Recursion

The os.walk function in Python is a powerful function. It generates the file names and sub-directory names in a directory tree by walking the tree. For each directory in the tree, it yields a 3-tuple (dirpath, dirnames, filenames).

It is not well-known that you can modify dirnames in the body of the os.walk() loop to manipulate the recursion!

I’ve seen programmers avoid using os.walk(), and hack their own version of it using recursive calls to os.listdir(), with various path manipulations in the process. It was rare that the programmer doing this was not familiar with os.walk(). More often than not, the reason was that the programmer wanted more control over the recursion. Unfortunately, if the programmer was aware that this can be done with os.walk(), she would probably use it and save time and sweat!

This specific feature is well documented in the Python os.walk docs. Seeing how under-used it is, I wanted to highlight it here, hoping it will serve someone out there 🙂 .

Continue Reading…