Tools for working with files


Useful for a temporary cd for use in a with statement:

with cd(‘/Library/’):


will switch temporarily, and then switch back when leaving.

music21.common.fileTools.readFileEncodingSafe(filePath, firstGuess='utf-8')

Slow, but will read a file of unknown encoding as safely as possible using the LGPL chardet package in music21.ext.

Let’s try to load this file as ascii – it has a copyright symbol at the top so it won’t load in Python3:

>>> import os
>>> c = str(common.getSourceFilePath() / 'common' / '')
>>> f = open(c)
>>> data =
Traceback (most recent call last):
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position ...:
    ordinal not in range(128)

That won’t do! now I know that it is in utf-8, but maybe you don’t. Or it could be an old humdrum or Noteworthy file with unknown encoding. This will load it safely.

>>> data = common.readFileEncodingSafe(c)
>>> data[0:30]
'# -*- coding: utf-8 -*-\n# ----'

Well, that’s nothing, since the first guess here is utf-8 and it’s right. So let’s give a worse first guess:

>>> data = common.readFileEncodingSafe(c, firstGuess='SHIFT_JIS') # old Japanese standard
>>> data[0:30]
'# -*- coding: utf-8 -*-\n# ----'

It worked!

Note that this is slow enough if it gets it wrong that the firstGuess should be set to something reasonable like ‘ascii’ or ‘utf-8’.

Return type