Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如果python中的目录中存在目录名,则查找文件_Python - Fatal编程技术网

如果python中的目录中存在目录名,则查找文件

如果python中的目录中存在目录名,则查找文件,python,Python,我正在尝试读取某个特定目录中的某个文件,如。 我正在尝试使用python2.7+版本。我的要求如下: 在输出文件夹中查找目录以B1234(这里1234是nr)开头 如果目录存在,则转到仅以TEST开头的目录_ 只读文件endswith YYYY.txt 但它可以驻留在子目录中(这里名称不重要) 我试图使下面的代码工作,但徒劳无功 for root, dirs, files in os.walk('output'): for file in files: if file.s

我正在尝试读取某个特定目录中的某个文件,如。 我正在尝试使用python2.7+版本。我的要求如下:

在输出文件夹中查找目录以B1234(这里1234是nr)开头 如果目录存在,则转到仅以TEST开头的目录_ 只读文件endswith YYYY.txt 但它可以驻留在子目录中(这里名称不重要) 我试图使下面的代码工作,但徒劳无功

for root, dirs, files in os.walk('output'):
    for file in files:
        if file.startswith('test') and file.endswith('_YYYY.txt'):
            try:
                f =  open(os.path.abspath(os.path.join(root,file)) , 'r')
            except:
                print 'oops'
问题是在这里我可以找到所有想要的文件,但也从不想要的目录。。 我想这样用

for dir in dirList:
if dir startswith(B1234)
for testdir in os.listdir(dir)
if dir.startswiht(TEST_)
goto dir
search for file

如果您需要更多信息,请询问:

我认为您需要在此处进行更改:

for root, dirs, files in os.walk('output'):
    for dir in dirs:
        if dir.startswith('B1234') is False:
            continue
        for r, drs, fls in os.walk(dir):
            # now write your code here

hello“os.walk(dir)中的r、drs、fls”将不起作用,因为os.walk将检索Parralel中的文件和目录。我需要先检查目录,然后如果匹配项只需要提取文件,记住我当前所在的目录。您也可以尝试在最内层的for循环中使用os.listdir()方法。如何使用以及如何解析和返回路径?要解决路径问题,请检查此模块:,特别是os.path.join()。并且os.listdir()很简单,只需将目录名作为参数传递,它将返回文件和目录的列表,然后匹配文件是否符合您的模式。