[英]Search all files with same name in a directory python
I Have a Question : I need to get paths of a file in a directory, I have a folder that contains other folders and other folders etc.... and each of them contains a file "tv.sas7bdat" I need to get every path to that file. 我有一个问题:我需要获取目录中文件的路径,我有一个包含其他文件夹和其他文件夹等的文件夹。。。每个文件夹都包含一个文件“ tv.sas7bdat”,我需要获取每个文件该文件的路径。 Thank you !!! 谢谢 !!!
You can try the following code, where PATH stands for the parent directory 您可以尝试以下代码,其中PATH代表父目录
import os
def getAlldirInDiGui(path,resultList):
filesList=os.listdir(path)
for fileName in filesList:
fileAbpath=os.path.join(path,fileName)
if os.path.isdir(fileAbpath):
getAlldirInDiGui(fileAbpath,resultList)
else:
if fileName=='tv.sas7bdat':
resultList.append(fileAbpath)
resultList = []
PATH = ""
getAlldirInDiGui(PATH,resultList)
If I get your problem right you can achieve your goal using Pythons's os.walk function, like so: 如果我正确解决了问题,则可以使用Python的os.walk函数实现目标,如下所示:
import os
for root, dirs, files in os.walk("<starting folder here>", topdown=False):
for name in files:
if name == "tv.sas7bdat":
print(os.path.join(root, name))
ps: as for comments in your question, next time please provide as many details possible in your question and provide code of your attempt, see the asking guidelines ps:关于您的问题的评论,下次请提供尽可能多的细节,并提供您尝试的代码,请参阅询问准则
Hope fully below code should work for you: 希望下面的代码完全可以为您工作:
import glob
initial_path = "c:\<intital folder location>"
files = [file for file in glob.glob(initial_path+ "tv.sas7bdat" , recursive=True)]
for f in files:
print(f)
You could use the os
python package combined with a recursive function to search through a certain directory 您可以结合使用os
python软件包和递归函数来搜索特定目录
import os
from os.path import isfile, join, isdir
def get_files_path(directory, paths):
for item in os.listdir(directory):
if isfile(join(directory, item)) and item == "tv.sas7bda":
paths.append(directory + item)
elif isdir(directory+item):
get_files_path(directory + item, paths)
return paths
directory_to_search = "./"
get_files_path(directory_to_search , [])
You can use os.walk()
您可以使用os.walk()
import os
for root, dirs, files in os.walk(os.getcwd()):
for f in files:
if f.find("tv.sas7bdat")>=0:
print(root,f)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.