2012-10-17 138 views
4

我有名爲「a1.txt」,「a2.txt」,「a3.txt」,「a4.txt」,「a5.txt」等文件。然後我有名爲「a1_1998」,「a2_1999」,「a3_2000」,「a4_2001」,「a5_2002」等的文件夾。將文件名匹配到文件夾名稱,然後移動文件

例如,我想在文件「a1.txt」&文件夾「a1_1998」之間進行連接。 (我猜我需要一個正規的表達來做到這一點)。然後使用shutil將文件「a1.txt」移動到文件夾「a1_1998」,將文件「a2.txt」移動到文件夾「a2_1999」等等中。我對正規表達的理解不夠。

import re 
##list files and folders 

r = re.compile('^a(?P') 
m = r.match('a') 
m.group('id') 

## 
##Move files to folders 

我稍微修改了下面的答案,使用shutil移動文件,做了伎倆!

import shutil 
import os 
import glob 

files = glob.glob(r'C:\Wam\*.txt') 

for file in files: 
    # this will remove the .txt extension and keep the "aN" 
    first_part = file[7:-4] 
    # find the matching directory 
    dir = glob.glob(r'C:\Wam\%s_*/' % first_part)[0] 
    shutil.move(file, dir) 

回答

5

您不需要正則表達式。

怎麼是這樣的:

import glob 
files = glob.glob('*.txt') 
for file in files: 
    # this will remove the .txt extension and keep the "aN" 
    first_part = file[:-4] 
    # find the matching directory 
    dir = glob.glob('%s_*/' % first_part)[0] 
    os.rename(file, os.path.join(dir, file)) 
+0

也許增加一個測試,如果第2個'glob.glob()'真的正好返回一個目錄名稱... – glglgl

+0

這種解決方案是非常具體的答案,而不是要做到這一點的最好辦法。你應該使用'os.path.splitext()'來獲得'(filename,extension)'對。 –

+0

@Inbar Rose,'splitext()'是更常用的解決方案,以防您需要從文件名中刪除擴展名。不過,我不確定這會永遠如此。 OP沒有具體說明。 –

0

有輕微的替代,考慮到因巴爾羅斯的建議。

import os 
import glob 

files = glob.glob('*.txt') 
dirs = glob.glob('*_*') 

for file in files: 
    filename = os.path.splitext(file)[0] 
    matchdir = next(x for x in dirs if filename == x.rsplit('_')[0]) 
    os.rename(file, os.path.join(matchdir, file)) 
+0

感謝Talvalin這應該做的伎倆,我只是在matchdir行遇到問題時,我添加到我的文件的路徑如下所示:import os import glob files = glob.glob(r'C:\ Wam \ *。docx') dirs = glob.glob(r'C:\ Wam \ * _ *') 是否有另一種指定工作目錄的方式? –

+0

使用雙引號指定目錄應修復該問題。例如:files = glob.glob(「C:\ Wam * .docx」) – Talvalin

相關問題