选择文件夹Python

时间:2015-11-10 17:16:26

标签: python directory

我是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文件,以执行值的缩放。后来我在两个文件之间做了其他数学运算符。

谢谢你的帮助!

1 个答案:

答案 0 :(得分: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