簡體   English   中英

python將壓縮的zip轉換為未壓縮的tar

[英]python convert compressed zip to uncompressed tar

我有一個壓縮的.zip文件,我想將其轉換為未壓縮的.tar文件。

我做了這個功能來做到這一點:

def decompress(filepath):
  devname = re.search("_(.+?)_.+?\.zip", filepath).group(1)
  with zipfile.ZipFile(filepath, 'r') as zip:
    path = os.path.join(start_dir, "Downloads", devname, str(os.path.basename(filepath))[:-4])
    zip.extractall(path)
  with tarfile.open(path + ".tar", 'w') as tar:
    for object in os.listdir(path):
      tar.add(os.path.join(path, object), arcname=object)
  time.sleep(2)
  shutil.rmtree(path, ignore_errors=False, onerror=onError)
  time.sleep(0.5)
  os.remove(filepath)
  return path + ".tar"

運行時出現此錯誤:

Traceback (most recent call last):
  File "File.py", line 195, in <module>
    main()
  File "File.py", line 184, in main
    dld = download()
  File "File.py", line 132, in download
    filename = decompress(os.path.join(start_dir, "Downloads", devname, filename
))
  File "File.py", line 103, in decompress
    shutil.rmtree(path, ignore_errors=False, onerror=onError)
  File "C:\Program Files (x86)\python27\lib\shutil.py", line 247, in rmtree
    rmtree(fullname, ignore_errors, onerror)
  File "C:\Program Files (x86)\python27\lib\shutil.py", line 247, in rmtree
    rmtree(fullname, ignore_errors, onerror)
  File "C:\Program Files (x86)\python27\lib\shutil.py", line 256, in rmtree
    onerror(os.rmdir, path, sys.exc_info())
  File "C:\Program Files (x86)\python27\lib\shutil.py", line 254, in rmtree
    os.rmdir(path)
WindowsError: [Error 145] The directory is not empty: 'C:\\Users\\Vaibhav\\Deskt
op\\Folder\\Downloads\\toro\\_toro_nightly_test\\system\\app'

這是我從https://stackoverflow.com/a/2656405/2518263獲得的onError:

def onError(func, path, exc_info):
    """
    Error handler for ``shutil.rmtree``.

    If the error is due to an access error (read only file)
    it attempts to add write permission and then retries.

    If the error is for another reason it re-raises the error.

    Usage : ``shutil.rmtree(path, onerror=onerror)``
    """
    if not os.access(path, os.W_OK):
        # Is the error an access error ?
        os.chmod(path, stat.S_IWUSR)
        func(path)
    else:
        raise

我只會在隨機情況下收到錯誤。 解壓縮功能的工作時間為75%。

我不知道為什么會收到此錯誤。 有人可以建議一種更好的方法來解決此錯誤或解決此錯誤。


我只是替換了:

shutil.rmtree(path, ignore_errors=False, onerror=onError)

有:

for root, dirs, files in os.walk(path, topdown=False):
    for name in files:
        filename = os.path.join(root, name)
        os.chmod(filename, stat.S_IWUSR)
        os.remove(filename)
    for name in dirs:
        os.rmdir(os.path.join(root, name))
  time.sleep(0.5)
  os.rmdir(path)

現在,它就像一種魅力。

編輯:沒關系! 我仍然會收到錯誤,但很少出現,現在大約有20%的時間!! 請幫忙!

編輯2:

好的,所以如果我解壓縮到一個臨時文件中就不會收到錯誤,所以我正在使用以下代碼:

import tempfile
def decompress(filepath):
  with zipfile.ZipFile(filepath) as zip:
    tmp = tempfile.mkdtemp(dir=os.getcwd())
    zip.extractall(tmp)
  with tarfile.open(filepath[:-4] + ".tar", 'w') as tar:
    for object in os.listdir(tmp):
      tar.add(os.path.join(tmp, object), arcname=object)
  time.sleep(1)
  shutil.rmtree(tmp)
  os.remove(filepath)
  return filepath[:-4] + ".tar"

我現在工作! (希望該錯誤不會再次發生)

編輯3:我又得到了錯誤! 這真的讓我感到不安。 請幫助某人。

操作系統中的某個進程似乎設法在您要刪除的目錄中創建另一個文件。

我建議您避免創建臨時文件,並將原始ZIP的解壓縮部分直接饋送到新的TAR文件中。

這需要將ZipInfo字段與TarInfo字段進行匹配,但這應該很簡單。

這是我的看法:

def zip2tar(zipname, tarname):
    zipf = zipfile.ZipFile(zipname, 'r')
    tarf = tarfile.TarFile(tarname, 'w')
    timeshift = int((datetime.datetime.now() -
                     datetime.datetime.utcnow()).total_seconds())
    for zipinfo in zipf.infolist():
        tarinfo = tarfile.TarInfo()
        tarinfo.name = zipinfo.filename
        tarinfo.size = zipinfo.file_size
        tarinfo.mtime = calendar.timegm(zipinfo.date_time) - timeshift
        if zipinfo.internal_attr & 1:
            tarinfo.mode = 0666
            tarinfo.type = tarfile.REGTYPE
        else:
            tarinfo.mode = 0777
            tarinfo.type = tarfile.DIRTYPE 
        infile = zipf.open(zipinfo.filename)
        tarf.addfile(tarinfo, infile)
    zipf.close()
    tarf.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM