使用python,如何在Test.txt文件的每一行中循环搜索Android.mk文件(如果找不到),请进入目录级别并再次搜索,直到找到文件?
/home/jenkins/workspace/art/build/apps/XYZ.cpp
在上面的路径中,Android.mk位于以下位置
/home/jenkins/workspace/art/build/apps/Android.mk
/home/jenkins/workspace/art/build/Android.mk
/home/jenkins/workspace/frameworks/base/rs/ABC.java
在上面的路径中,Android.mk位于以下位置
/home/jenkins/workspace/frameworks/Android.mk
Test.txt
/home/jenkins/workspace/art/build/apps/XYZ.cpp /home/jenkins/workspace/frameworks/base/rs/ABC.java
DesireOutput.txt
/home/jenkins/workspace/art/build/apps/Android.mk
/home/jenkins/workspace/frameworks/Android.mk
MyTry
with open('/data/jenkins/workspace/Experiments/Test.txt','r') as f:
for apps in f.readlines():
print(apps.strip())
dirs = os.listdir( apps.strip() )
for file in dirs:
#print file
if file == 'Android.mk':
print "Android.mk found"
else:
os.chdir(apps.strip())
apps.strip()
print "Android.mk not found"
答案 0 :(得分:1)
您的脚本未使用os.chdir('../')
升级。这是一个在while循环内实现该脚本的脚本。您在每个循环中调用os.chdir(apps.strip())
而不是os.chdir('../')
来上移一个级别。
with open('/data/jenkins/workspace/Experiments/Test.txt','r') as f:
for apps in f.readlines():
os.chdir(apps.strip()) # move into the folder here
print("Starting search in {}".format(apps.strip()))
found = False
while not found:
dirs = os.listdir(os.getcwd()) # print files in current directory (no argument needed)
for file in dirs:
if file == 'Android.mk':
print("Android.mk found")
found = True
break # end our for loop to save computations
if not found:
os.chdir("../") # move up a level for the next iteration of while loop
print("Android.mk not found...going up a level")
此外,dirs = os.listdir()
应该没有参数,因此它将用于当前文件夹(我们已更改为该文件夹)。否则,无论您在文件系统中的哪个位置,它都将返回相同的结果。