2013-01-31 47 views
0

我正在上傳包含文本文件的文件夾的壓縮文件夾,但未檢測到壓縮的文件夾是目錄。我認爲這可能與要求在os.path.isdir調用中的絕對路徑有關,但似乎無法弄清楚如何實現它。目錄在Python中未被識別

  zipped = zipfile.ZipFile(request.FILES['content']) 
      for libitem in zipped.namelist(): 
       if libitem.startswith('__MACOSX/'): 
        continue 
       # If it's a directory, open it 
       if os.path.isdir(libitem): 
        print "You have hit a directory in the zip folder -- we must open it before continuing" 
        for item in os.listdir(libitem): 

回答

0

您上傳的文件是一個zip文件,它只是其他文件和目錄的容器。所有Python os.path函數都在本地文件系統上的文件上運行,這意味着您必須首先提取zip的內容,然後才能使用os.pathos.listdir

不幸的是,不可能從ZipFile對象中確定一個條目是否用於文件或目錄。

重寫或代碼,其第一做的提取物可以是這個樣子:

import tempfile 

# Create a temporary directory into which we can extract zip contents. 
tmpdir = tempfile.mkdtemp() 
try: 
    zipped = zipfile.ZipFile(request.FILES['content']) 
    zipped.extractall(tmpdir) 

    # Walk through the extracted directory structure doing what you 
    # want with each file. 
    for (dirpath, dirnames, filenames) in os.walk(tmpdir): 
     # Look into subdirectories? 
     for dirname in dirnames: 
      full_dir_path = os.path.join(dirpath, dirname) 
      # Do stuff in this directory 
     for filename in filenames: 
      full_file_path = os.path.join(dirpath, filename) 
      # Do stuff with this file. 
finally: 
    # ... Clean up temporary diretory recursively here. 
0

當運行你想要使用的腳本os.path時,通常會讓事情處理相對路徑等。

在我看來,你正在從Zipfile中讀取你沒有實際解壓縮的項目,所以你爲什麼會期望文件/目錄存在?

通常我會print os.getcwd()找出我在哪裏,並且還使用os.path.join加入數據目錄的根目錄,無論這個目錄是否包含我無法辨別的腳本。使用類似scriptdir = os.path.dirname(os.path.abspath(__file__))

我期望你會做這樣的事情

libitempath = os.path.join(scriptdir, libitem) 
if os.path.isdir(libitempath): 
    .... 

但我在你在做什麼,因爲它是對我來說有點不清楚猜測。