[英]Using glob.glob to find files in multiple folders through a given path?
So I'm trying to use glob.glob to to go through a user-given path to Python and then finding all subsequent folders for a .txt. 因此,我尝试使用glob.glob遍历用户提供的Python路径,然后查找.txt的所有后续文件夹。 Currently, below, is what I have but it doesn't seem to work.
目前,下面是我所拥有的,但似乎不起作用。
fileName = raw_input("> ")
listOfTxt = []
for files in glob.glob(os.path.join(fileName, "\\Folder\\*\\*\\*.txt")):
listOfTxt.append(files) # add it to the list
I'm not sure how to get this to work, or I'm just not understanding the glob.glob with os.path. 我不确定如何使它工作,或者我只是不了解os.path的glob.glob。
If you simply want a list of all .txt
files in os.path.join(user_dir,'Folder')
, then os.walk
is probably a better way to go: 如果您只是想要
os.path.join(user_dir,'Folder')
中所有.txt
文件的列表,那么os.walk
可能是一个更好的选择:
import os
user_dir = os.path.join(raw_input('> '),'Folder')
file_list = [ ]
for dirpath,_,filenames in os.path.walk(user_dir):
for name in filenames:
if name.endswith('.txt'):
file_list.append(os.path.join(user_dir,dirpath,name))
you join the given name with a path, which is strange and probably not what you want. 您将给定名称与路径连接起来,这很奇怪,可能不是您想要的。 You probably want something like
您可能想要类似
glob.glob(os.path.join("\\Folder\\*\\*\\",fileName+".txt"))
? ?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.