在使用 Python 的 tarfile 库找到更简单且可能更快的解决方案之前,我在 linux 上苦苦挣扎了很长时间。
- 使用 glob.glob 搜索所需的文件路径
- 以附加模式创建新存档
- 将每个文件路径添加到此存档
- 关闭存档
这是我的代码示例:
import tarfile
import glob
from tqdm import tqdm
filepaths = glob.glob("Images/7 *.jpeg")
n = len(filepaths)
print ("{} files found.".format(n))
print ("Creating Archive...")
out = tarfile.open("Images.tar.gz", mode = "a")
for filepath in tqdm(filepaths, "Appending files to the archive..."):
try:
out.add(filepath)
except:
print ("Failed to add: {}".format(filepath))
print ("Closing the archive...")
out.close()
查找 16222 个文件路径并创建存档总共花费了大约 12 秒,但是,这主要是通过简单地搜索文件路径来完成的。创建包含 16000 个文件路径的 tar 归档文件只用了 7 秒。使用一些多线程,这可能会更快。
如果您正在寻找多线程实现,我已经制作了一个并将其放置在此处:
import tarfile
import glob
from tqdm import tqdm
import threading
filepaths = glob.glob("Images/7 *.jpeg")
n = len(filepaths)
print ("{} files found.".format(n))
print ("Creating Archive...")
out = tarfile.open("Images.tar.gz", mode = "a")
def add(filepath):
try:
out.add(filepath)
except:
print ("Failed to add: {}".format(filepath))
def add_multiple(filepaths):
for filepath in filepaths:
add(filepath)
max_threads = 16
filepaths_per_thread = 16
interval = max_threads * filepaths_per_thread
for i in tqdm(range(0, n, interval), "Appending files to the archive..."):
threads = [threading.Thread(target = add_multiple, args = (filepaths[j:j + filepaths_per_thread],)) for j in range(i, min([n, i + interval]), filepaths_per_thread)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print ("Closing the archive...")
out.close()
当然,你需要确保 和 的值max_threads
是filepaths_per_thread
优化的;创建线程需要时间,因此对于某些值,时间实际上可能会增加。最后要注意的是,由于我们使用的是附加模式,如果一个新存档尚不存在,我们将自动创建一个具有指定名称的新存档。但是,如果一个已经存在,它只会添加到预先存在的存档中,而不是重置它或创建一个新存档。