import os import sys # rm -r impdir; python3 thisfile.py # fail # rm -r impdir; python3 thisfile.py fix1 # success # rm -r impdir; python3 thisfile.py fix2 # success # rm -r impdir; python3 thisfile.py # fail # python3 thisfile.py # success FIX1 = 'fix1' in sys.argv FIX2 = 'fix2' in sys.argv if FIX1: import tarfile # with this here the import works LIBDIR = 'impdir' def extract(): if not FIX1: import tarfile # with this here the import fails os.mkdir(LIBDIR) open(os.path.join(LIBDIR, 'impfile.py'), 'w') if not FIX2: sys.path.append(LIBDIR) # with this here the import fails if os.path.exists(LIBDIR): print('%s already exists' % LIBDIR) else: extract() if FIX2: sys.path.append(LIBDIR) # with this here the import works import impfile # <------ this is the import that fails print('Imported impfile')