gpt4 book ai didi

python 从目录树打印 .c 文件的路径名

转载 作者:太空宇宙 更新时间:2023-11-03 16:20:40 25 4
gpt4 key购买 nike

我是Python初学者。我正在尝试使用包含可变深度的测试用例(.文件)的目录树,例如,测试(顶级目录)有2个子级test1和测试2。test1还有进一步的分支t1和t2,其中包含t1.c和t2分别为.c。类似地,test2 有 2 个子项 test21 和 test22。测试 21 有 t3 和 t4,其中包含 t3.c 和 t4.c 回复。 test22 有 t5 和 t6,其中有 t5.c 和 t6.c。我正在尝试搜索 .c 文件,然后使用递归打印其路径。

我收到的错误是代码仅跟踪一个分支,并且不会返回到上一级别来遍历其他分支。请在这里帮助我。

以下是我的代码:

# assume, at no level folders and .c files are present at the same time

import os import fnmatch


# move to test directory
os.chdir('/home/gyadav/test')


# function to create a list of sub directories
def create_subdir_list():
subdirs = os.listdir('.')
len_subdirs = len(subdirs) - 1
# while i != length
for i in range(0, len_subdirs):
# move to next folder
os.chdir(subdirs[i])
print os.getcwd()
subdirs1 = (os.listdir('.'))
print subdirs1
# call function - open thedirectory and check for .c file
open_dir('.')


# definition of check for . c file
def check_for_c():
cfile = fnmatch.filter(os.listdir('.'), '*.c')
# if file found
if len(cfile) != 0:
# save the path
path = os.path.dirname(os.path.abspath(cfile[0]))
print path
os.chdir('..')
print os.getcwd()

else:
create_subdir_list()


def open_dir(name):
check_for_c()
open_dir('.')

最佳答案

最好用自己的方式来练习Python。但有效的方法是:

>>> PATH = '/home/sijan/Desktop/'
>>> import os
>>> from glob import glob
>>> result = [y for x in os.walk(PATH) for y in glob(os.path.join(x[0], '*.py'))]

它将列出给定路径中文件夹中的所有 .py 文件。

关于python 从目录树打印 .c 文件的路径名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38502657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com