[英]How to create full compressed tar file using Python?
如何在 Python 中創建壓縮后的 .tar.gz 文件?
為整個目錄樹構建一個.tar.gz
(又名.tgz
):
import tarfile
import os.path
def make_tarfile(output_filename, source_dir):
with tarfile.open(output_filename, "w:gz") as tar:
tar.add(source_dir, arcname=os.path.basename(source_dir))
這將創建一個 gzipped tar 存檔,其中包含一個與source_dir
名稱和內容相同的頂級文件夾。
import tarfile
tar = tarfile.open("sample.tar.gz", "w:gz")
for name in ["file1", "file2", "file3"]:
tar.add(name)
tar.close()
如果要創建 tar.bz2 壓縮文件,只需將文件擴展名替換為“.tar.bz2”,將“w:gz”替換為“w:bz2”。
您使用mode='w:gz'
調用tarfile.open ,意思是“打開以進行 gzip 壓縮寫入”。
您可能希望使用.tar.gz
結束文件名( open
的name
參數),但這不會影響壓縮能力。
順便說一句,您通常使用'w:bz2'
模式獲得更好的壓縮,就像tar
通常使用bzip2
壓縮比使用gzip
壓縮更好。
以前的答案建議使用tarfile
Python 模塊在 Python 中創建.tar.gz
文件。 這顯然是一個很好的 Python 風格的解決方案,但它在歸檔速度方面存在嚴重缺陷。 這個問題提到tarfile
比 Linux 中的tar
實用程序慢大約兩倍。 根據我的經驗,這個估計是非常正確的。
因此,為了更快地歸檔,您可以使用tar
命令使用subprocess
模塊:
subprocess.call(['tar', '-czf', output_filename, file_to_archive])
除了@Aleksandr Tukallo 的回答,您還可以獲得輸出和錯誤消息(如果發生)。 以下答案很好地解釋了使用tar
壓縮文件夾。
import traceback
import subprocess
try:
cmd = ['tar', 'czfj', output_filename, file_to_archive]
output = subprocess.check_output(cmd).decode("utf-8").strip()
print(output)
except Exception:
print(f"E: {traceback.format_exc()}")
在這個 tar.gz 文件中壓縮在打開的視圖目錄中解決使用 os.path.basename(file_directory)
import tarfile
with tarfile.open("save.tar.gz","w:gz") as tar:
for file in ["a.txt","b.log","c.png"]:
tar.add(os.path.basename(file))
它在 tar.gz 文件中的使用 壓縮在目錄中
對@THAVASI.T 的答案進行了較小的更正,其中省略了顯示“tarfile”庫的導入,並且沒有定義第三行中使用的“tar”對象。
import tarfile
with tarfile.open("save.tar.gz","w:gz") as tar:
for file in ["a.txt","b.log","c.png"]:
tar.add(os.path.basename(file))
shutil.make_archive對於文件和目錄都非常方便(遞歸添加到存檔中的內容):
import shutil
compressed_file = shutil.make_archive(
base_name='archive', # archive file name w/o extension
format='gztar', # available formats: zip, gztar, bztar, xztar, tar
root_dir='path/to/dir' # directory to compress
)
只是重申@George V. Reilly 的出色回答,但形式更清晰......
import tarfile
fd_path="/some/folder/path/"
fl_name="some_file_name.ext"
targz_fd_path_n_fl_name="/some/folder/path/some_file_name.tar.gz"
with tarfile.open(targz_fd_path_n_fl_name, "w:gz") as tar:
tar.add(fd_path + fl_name, fl_name)
正如@Brōtsyorfuzthrāx 所指出的(但以另一種方式),如果您將“add”方法的第二個參數保留下來,那么它將在 tar 文件中為您提供fd_path + fl_name
的完整路徑結構。
當然你可以用...
import tarfile
import os
fd_path_n_fl_name="/some/folder/path/some_file_name.ext"
targz_fd_path_n_fl_name="/some/folder/path/some_file_name.tar.gz"
with tarfile.open(targz_fd_path_n_fl_name, "w:gz") as tar:
tar.add(fd_path_n_fl_name, os.path.basename(fd_path_n_fl_name))
...如果您不想使用或不想將文件夾路徑和文件名分開。
謝謝!
.
和..
在壓縮文件中!注意(感謝 MaxTruxa):
這個答案很容易受到 shell 注入的影響。 請閱讀文檔中的安全注意事項。 如果
shell=True
,切勿將未轉義的字符串傳遞給subprocess.run
、subprocess.call
等。 使用shlex.quote
轉義(僅限 Unix shell)。我在本地使用它- 所以它對我的需求有好處。
subprocess.call(f'tar -cvzf {output_filename} *', cwd=source_dir, shell=True)
cwd
參數在壓縮之前更改目錄 - 這解決了點的問題。
shell=True
允許使用通配符( *
)
WORKS 也適用於遞歸目錄
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.