2015-11-10 125 views
-1

我是python的新手,想要編碼文件夾中的特定特徵,然後對所需文件夾內的內容執行操作。這是如下的一個示例:選擇文件夾Python

Path = "./Desktop/Example/"   #Input Directory 
A_files = []                  
for dirName, subdirList, fileList in os.walk(Path):        
    for filename in fileList:              
     if "[A]" in subdirList() 
     if ".txt" in filename.lower():             
      A_files.append(os.path.join(dirName,filename)) 

#Perform Mathematical Operators for A_files only 

B_files = []                  
for dirName, subdirList, fileList in os.walk(Path):        
    for filename in fileList:              
     if "[B]" in subdirList() 
     if ".txt" in filename.lower():             
      B_files.append(os.path.join(dirName,filename)) 

#Perform Mathematical Operators for B_files only 

#Perform Mathematical Operators between A_files and B_files together 

在文件夾「實施例」是子文件夾:程序hello_world [A]和程序hello_world [B]和我要訪問的每個文件夾中的所有.txt文件個別地在第一執行縮放的價值。後來我在兩個文件之間做了其他數學運算符。

謝謝你的幫助!

+3

你的問題是什麼? – Kevin

+0

如何根據名稱的一部分選擇文件夾?就像在最後一條if語句中我只能選擇.txt文件一樣,我只想選擇包含[A]的文件夾 –

+0

我認爲'glob'模塊可以進行通配符式的部分匹配。我自己並沒有使用它。 – Kevin

回答

0

我想你問的是這樣的:

Path = "./Desktop/Example/"   #Input Directory 
A_files = []                  
for dirName, subdirList, fileList in os.walk(Path):        
    for filename in fileList:              
     if "[A]" in dirName: 
      if ".txt" in filename.lower():             
       A_files.append(os.path.join(dirName,filename)) 

#Perform Mathematical Operators for A_files only 

B_files = []                  
for dirName, subdirList, fileList in os.walk(Path):        
    for filename in fileList:              
     if "[B]" in dirName: 
      if ".txt" in filename.lower():             
       B_files.append(os.path.join(dirName,filename)) 

#Perform Mathematical Operators for B_files only 
for f in B: 
    data = open(filename).read() 
    # Do stuff 

#Perform Mathematical Operators between A_files and B_files together 
for index, file in enumerate(A): 
    dataA = open(A[i]).read() 
    dataB = open(B[i]).read() 
    # Do something 

由於dirname是一個字符串,可以使用in檢查其內容。

然後,您可以遍歷您的A[]B[]來完成您的數學運算,並使用枚舉對兩個索引進行迭代。看到這裏:Accessing the index in Python 'for' loops