2016-06-09 252 views
1

我有一個很大的沒有。名稱僅爲數字的zip文件。現在,每個zip文件都包含一個與zip文件具有相同名稱的文件夾(即,如果zip文件的名稱是1234.zip,那麼文件夾的名稱也將是1234)。此文件夾還包含一個文本文件,其中包含atextfile.txt,其中包含指定zip年份的整數,例如2016.
現在我想將每個zip文件移動到其各自的文件夾,即一年一度。意思是我想要做的是提取年的價值,即2016年,並創建一個名爲2016的文件夾,將zip文件移動到此文件夾,併爲下一個zip文件執行相同的操作。
我成功檢索年份並將其存儲在名爲year的變量中。
到目前爲止我寫的代碼:如何將一個zip文件移動到一個文件夾

import glob 
    import os 
    import zipfile 
    import shutil 
    for zip_name in glob.glob('[0-9]*.zip'): 
     z=zipfile.ZipFile(zip_name) 
     # To remove '.zip' from the name of zip_name 
     subdir = zip_name[:-4] 
     with z.open('{}/atextfile.txt'.format(subdir)) as f: 
      for line in f: 
       for word in line: 
        year = word 
        # the file atextfile.txt has many lines containing many      integer of which the first line represents the year. 
        break 
       else: 
        continue 
       break 
     z.close() 
     if not os.path.exists(year): 
      os.makedirs(year) 
     shutil.move(zip_name, year) 


這是給出了錯誤:
WindowsError:[錯誤32],因爲它被另一個進程的進程不能訪問該文件。
我用Google搜索了一下,然後我才知道這背後的原因是因爲我的zip文件已經打開。但我無法解決這個問題,所以請幫助。
更新:問題已解決我將zip_name和year存儲在文本文件中,然後在另一個程序中讀取文本文件並將相應的zip文件移至其year文件夾。感謝您的回覆。

+0

確保您沒有文件夾打開。看看你的活動計劃。你打開文件夾了嗎? – TheLazyScripter

回答

0

Try with subprocess and ROBOCOPY:

import glob 
import os 
import zipfile 
import subprocess 

for zip_name in glob.glob('[0-9]*.zip'): 
    z = zipfile.ZipFile(zip_name) 
    # To remove '.zip' from the name of zip_name 
    subdir = zip_name[:-4] 
    with z.open('{}/atextfile.txt'.format(subdir)) as f: 
     for line in f: 
      for word in line: 
       year = word 
       break 
      else: 
       continue 
      break 
    z.close() 
    if not os.path.exists(year): 
     os.makedirs(year) 
    command = 'ROBOCOPY {} {} /S /MOVE'.format(zip_name, year) 
    subprocess.call(command) 
+0

它顯示錯誤:錯誤123(0x0000007B)訪問源目錄E:\ Meta_files \ 1.zip \ 文件名,目錄名稱或卷標語法不正確。 –

0

我下面的作品,似乎與你都拿到年度途中的一個問題。

import glob 
import os 
import zipfile 
import shutil 

for zip_name in glob.glob('[0-9]*.zip'): 
    z = zipfile.ZipFile(zip_name) 
    subdir = os.path.splitext(zip_name)[0] 

    with z.open('{}/atextfile.txt'.format(subdir)) as f: 
     for line in f: 
      line = line.strip() 
      if line.lower().startswith("date"): 
       year = line.split('-')[-1] 
       break 

    if not os.path.exists(year): 
     os.makedirs(year) 

    z.close() 
    shutil.move(zip_name, year) 

而且,最好是使用os.path.splitext()函數來提取您的zip_name

+0

我試過了,但它仍然不能正常工作。文件中的數據格式稍有不同。它包含許多行,每行看起來像這樣:attribute = value ex。日期= 2013年7月23日。所以我不得不提取2013年的第一個使用:在line.split('=')中的單詞,然後在某些情況下,它是這樣的:Date = 23-JUL-2013,所以我必須寫:word = word。跳閘()。然後,我必須找到Date這個詞,然後將整個日期存儲在一個變量中,例如變量具有值23-JUL-2013,然後提取我編寫year = variable [: - 4]的年份。希望這有助於某種方式。 –

+0

您的代碼是否創建了正確的文件夾?即如果你註釋掉'shutil.move()'它是否創建了一切? –

+0

我已更新腳本以使用您的文件格式。 –

相關問題