|
618 | 618 | { |
619 | 619 | "data": { |
620 | 620 | "text/plain": [ |
621 | | - "['c', 'h', 'f', 'a', 'g', 'd', 'b', 'e']" |
| 621 | + "['d', 'e', 'h', 'g', 'b', 'a', 'c', 'f']" |
622 | 622 | ] |
623 | 623 | }, |
624 | 624 | "execution_count": null, |
|
1010 | 1010 | "def untar_dir(fname, dest):\n", |
1011 | 1011 | " \"untar `file` into `dest`\"\n", |
1012 | 1012 | " with tempfile.TemporaryDirectory(dir='.') as d:\n", |
1013 | | - " d = Path(d)\n", |
1014 | | - " with open(fname, 'rb') as f:\n", |
1015 | | - " with tarfile.open(mode='r:gz', fileobj=f) as t:\n", |
1016 | | - " t.extractall(d)\n", |
1017 | | - " next(d.iterdir()).rename(dest)" |
| 1013 | + " shutil.unpack_archive(fname, d)\n", |
| 1014 | + " ls = Path(d).ls()\n", |
| 1015 | + " if len(ls) == 1: shutil.move(str(ls[0]), dest)\n", |
| 1016 | + " else: shutil.move(str(d), dest/remove_suffix(Path(fname).stem, '.tar'))" |
| 1017 | + ] |
| 1018 | + }, |
| 1019 | + { |
| 1020 | + "cell_type": "markdown", |
| 1021 | + "metadata": {}, |
| 1022 | + "source": [ |
| 1023 | + "If the contents of `fname` contain just one file or directory, it is placed directly in `dest`:" |
| 1024 | + ] |
| 1025 | + }, |
| 1026 | + { |
| 1027 | + "cell_type": "code", |
| 1028 | + "execution_count": null, |
| 1029 | + "metadata": {}, |
| 1030 | + "outputs": [], |
| 1031 | + "source": [ |
| 1032 | + "def test_untar(foldername, **kwargs):\n", |
| 1033 | + " with tempfile.TemporaryDirectory() as d:\n", |
| 1034 | + " nm = os.path.join(d, 'a')\n", |
| 1035 | + " shutil.make_archive(nm, 'gztar', **kwargs)\n", |
| 1036 | + " with tempfile.TemporaryDirectory() as d2:\n", |
| 1037 | + " d2 = Path(d2)\n", |
| 1038 | + " untar_dir(nm+'.tar.gz', d2)\n", |
| 1039 | + " test_eq(d2.ls(), [d2/foldername])" |
| 1040 | + ] |
| 1041 | + }, |
| 1042 | + { |
| 1043 | + "cell_type": "code", |
| 1044 | + "execution_count": null, |
| 1045 | + "metadata": {}, |
| 1046 | + "outputs": [], |
| 1047 | + "source": [ |
| 1048 | + "# using `base_dir` in `make_archive` results in `images` directory included in file names\n", |
| 1049 | + "test_untar('images', base_dir='images')" |
| 1050 | + ] |
| 1051 | + }, |
| 1052 | + { |
| 1053 | + "cell_type": "markdown", |
| 1054 | + "metadata": {}, |
| 1055 | + "source": [ |
| 1056 | + "If the contents of `fname` contain multiple files and directories, a new folder in `dest` is created with the same name as `fname` (but without extension):" |
| 1057 | + ] |
| 1058 | + }, |
| 1059 | + { |
| 1060 | + "cell_type": "code", |
| 1061 | + "execution_count": null, |
| 1062 | + "metadata": {}, |
| 1063 | + "outputs": [], |
| 1064 | + "source": [ |
| 1065 | + "# using `root_dir` in `make_archive` results in `images` directory *not* included in file names\n", |
| 1066 | + "test_untar('a', root_dir='images')" |
1018 | 1067 | ] |
1019 | 1068 | }, |
1020 | 1069 | { |
|
0 commit comments