python 从目录树中打印 .c 文件的路径名
python printing the path names of .c files from a directory tree
我是 Python 的初学者。
我正在尝试使用包含可变深度的测试用例(.files)的目录树,例如,测试(顶级目录)有 2 children test1 和 test 2。test1 有进一步的分支 t1 和 t2 其中包含 t1.c 和 t2.c 分别。类似地,test2 有 2 children 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 的初学者。 我正在尝试使用包含可变深度的测试用例(.files)的目录树,例如,测试(顶级目录)有 2 children test1 和 test 2。test1 有进一步的分支 t1 和 t2 其中包含 t1.c 和 t2.c 分别。类似地,test2 有 2 children 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 文件。