Should be slightly quicker with large numbers of files. Also moved socket import to the top as it will always be imported.