Programming: Useful file tools in Python - spinalcordtoolbox/spinalcordtoolbox GitHub Wiki

Most file commands can be found here and here

Most common file commands

  • cp filename path --> shutil.copy(filename, path)
  • rm -rf path --> shutil.rmtree(path, ignore_errors=True)
  • mv filepath1 filepath2 --> shutil.move(filepath1, filepath2)
    • Note: Do not use os.rename! Instead, use shutil.move for this too, because os.rename has an issue that causes problems with tmp_path on CI, as well as any users who have files spread across different filesystems.
  • status, path_sct = commands.getstatusoutput('echo $SCT_DIR') --> path_sct = os.environ.get('SCT_DIR')

Differences between os.path functions and pathlib.Path methods

  • Note that os.path.abspath() corresponds to pathlib.Path.resolve(), not pathlib.Path.absolute()! This is because of the different handling of .. inside paths.