2016-02-12 47 views
0

我有他們的許多修改部分文件大型目錄整理文件,我想遞歸地爲每個部分新的文件夾,然後將所有相關的文件移動到該文件夾​​。我試圖通過隔離一個7位數字來做到這一點,這個數字可以用作零件的標識符,所有相關的文件名也會包含這個數字。創建子目錄和基於文件名PYTHON

import os 
import shutil 
import csv 
import glob 
from fnmatch import fnmatch, filter 
from os.path import isdir, join 
from shutil import copytree, copy2, Error, copystat 
from shutil import copytree, ignore_patterns 


dirname = ' ' 

# pattern = '*???????*' 

for root, dirs, files in os.walk(dirname): 
    for fpath in files: 
     print(fpath) 
     if fpath[0:6].isdigit(): 
      matchdir = os.mkdir(os.path.join(os.path.dirname(fpath))) 
      partnum = str(fpath[0:6]) 
      pattern = str(partnum) 
      filematch = fnmatch(files, pattern) 
      print(filematch) 
      shutil.move(filematch, matchdir) 

這是我到目前爲止,基本上我不知道如何獲取原始文件名並將其用作其餘文件的匹配模式。我想用於這個匹配模式的原始文件名只是一個7位數的數字,並且所有相關文件都可能有其他字符(例如REV-2)。

+0

你在哪裏遇到麻煩?您已成功從文件名的前面拉出7位數字,將其存儲在** partnum **和** pattern **中,並查找包含該7位數字符串的其他文件。原始文件名在** fpath **中仍然安全。這是什麼部分不起作用,而它做的是什麼? – Prune

回答

1

不要overthink它

我想你弄不清什麼os.walk()給你 - 重新檢查docsdirsfiles都只是一個名的目錄/文件,而不是完整的路徑名單。

這是我的建議。假設你已經從一個目錄佈局是這樣的:

directory1 
    1234567abc.txt 
1234567abc.txt 
1234567bcd.txt 
2234567abc.txt 
not-interesting.txt 

而想要的東西,如來結束:

directory1 
    1234567 
     abc.txt 
1234567 
    abc.txt 
    bcd.txt 
2234567 
    abc.txt 
not-interesting.txt 

如果這是正確的,那麼就沒有必要複賽在目錄中的文件,只需對每個文件分別進行操作,並僅在零件目錄不存在的情況下進行操作。我也將使用正則表達式來做到這一點,所以像:

import os 
import re 
import shutil 

for root, dirs, files in os.walk(dirname): 
    for fname in files: 
     # Match a string starting with 7 digits followed by everything else. 
     # Capture each part in a group so we can access them later. 
     match_object = re.match('([0-9]{7})(.*)$', fname) 
     if match_object is None: 
      # The regular expression did not match, ignore the file. 
      continue 

     # Form the new directory path using the number from the regular expression and the current root. 
     new_dir = os.path.join(root, match_object.group(1)) 
     if not os.path.isdir(new_dir): 
      os.mkdir(new_dir) 

     new_file_path = os.path.join(new_dir, match_object.group(2)) 

     # Or, if you don't want to change the filename, use: 
     new_file_path = os.path.join(new_dir, fname) 

     old_file_path = os.path.join(root, fname) 
     shutil.move(old_file_path, new_file_path) 

需要注意的是,我有:

  • 交換條件的意義上,我們馬上繼續循環,如果該文件是不有趣。這是一種有用的模式,用於確保您的代碼不會過度縮進。
  • 改變的fpath名稱fname。這是因爲它不是路徑,而只是文件的名稱,所以最好稱它爲fname

請澄清問題,如果這不是你的意思!

[編輯],以顯示如何將文件複製,而不改變其名稱。

+0

謝謝!我怎麼能改變這個以包含不以數字開頭的文件?我嘗試在([0-9] {7})(。*)$之前添加'*',但出現錯誤 – Darya

+0

由於某些原因,當文件移過來時,它們的名稱(即目錄名稱)被刪除。我認爲代碼是從文件名中提取字符來創建目錄名,但我不希望文件名被改變。我怎樣才能解決這個問題? – Darya

+0

如果你想匹配只包含7個數字的文件,那麼不用're.match(pattern,string)''你可以做're.search(pattern,string)',如果'string'包含'模式'在任何地方。爲了更好地理解正則表達式,請查看[regular-expression-info tutorial](http://www.regular-expressions.info/tutorial.html),這是我學習的方式,並且確保閱讀python [正則表達式文檔](https://docs.python.org/2/library/re.html)。 – daphtdazz

相關問題