Instead of using plain python strings and appending to them, use 'io.StringIO' which is a data structure meant to be used for i/o. This should increase performance compared to plain strings.
dir_fd
os.scandir()