用python导航文件夹 [英] navigate folders with python
问题描述
我有一个文件夹ROOT,并且在许多不同的文件夹中(假设N),为简单起见,我称F1,F2等...
我需要使用这些文件夹中的文件。
如果我只有一个文件夹,我知道我可以做:
os.chdir(。)#我在ROOT
中为glob.glob( *。txt)中的文件名工作:
#我可以使用第i个文件...
但是我需要做的是这样的(伪代码):
os.chdir(。)#我正在ROOT
$ p中处理数据$ p>
中进行ROOT中的第一个操作:#for ROOT主文件夹中的每个文件夹
对于Fi-th( *。txt)中的文件名:#我仅选择具有此扩展名的文件
#在第i个文件
我的意思是我需要进入第一个文件夹(F1)并处理所有文件(或者可能的所有.txt文件)在F2中并处理所有文件。...
解决方案
os.walk
将执行目录的递归操作,而fnmatch.filter
将匹配文件名模式。简单的例子:import os
import fnmatch
用于路径,目录,文件os.walk('。'):fnmatch.filter(files,'*。txt')中$ f的
:
fullname = os.path.abspath(os.path.join(path,f ))
print(全名)
I have a folder ROOT and inside many different folders (let's assume N), that for sake of simplicity I call F1, F2 and so on...
I need to work with the file inside these folders. If I have only one folder I know that I can do:
os.chdir(".") #I'm workingo in ROOT for filename in glob.glob("*.txt"): #I can work with the i-th file...
But what I need to do is something like this (pseudo-code like):
os.chdir(".") #I'm working in ROOT for F-i-th in ROOT: #for each folder in the ROOT main folder for filename in F-i-th("*.txt"): #I select only the file with this extention #process data inside i-th file
I mean that I need to go inside the first folder (F1) and process all the file (or if it is possible all the .txt file), after I should go inside the F2 and process all the file....
解决方案
os.walk
will perform recursion of a directory andfnmatch.filter
will match filename patterns. Simple example:import os import fnmatch for path,dirs,files in os.walk('.'): for f in fnmatch.filter(files,'*.txt'): fullname = os.path.abspath(os.path.join(path,f)) print(fullname)
这篇关于用python导航文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!