1 回答
TA贡献1802条经验 获得超4个赞
您需要break在您的for-else. 最小修改是:
def main():
lvl1 = ['Typ','GFP2']
lvl2 = ['A0','A1']
lvl3 = ['SCAN','MBIST']
project = input("Enter project: ")
#Validation
for s in lvl1:
if s == project:
src1 = 'IDC\\{}'.format(s)
stepping = input("Enter Stepping: ")
for l2 in lvl2:
if l2 == stepping:
#shutil.copytree()
src2 = src1+'\\{}'.format(l2)
thirdlvl = input("Enter SCAN/MBIST: ")
for l3 in lvl3:
if l3 == thirdlvl:
src3 = src2+'\\{}'.format(l3)
print(src3)
break
else:
print("Stepping not found")
break
else:
print("Project name not found")
for-loop您还可以通过以下方式摆脱
def main():
lvl1 = ['Typ','GFP2']
lvl2 = ['A0','A1']
lvl3 = ['SCAN','MBIST']
project = input("Enter project: ")
#Validation
if project in lvl1:
src1 = 'IDC\\{}'.format(project)
stepping = input("Enter Stepping: ")
if stepping in lvl2:
#shutil.copytree()
src2 = src1+'\\{}'.format(stepping)
thirdlvl = input("Enter SCAN/MBIST: ")
if thirdlvl in lvl3:
src3 = src2+'\\{}'.format(thirdlvl)
print(src3)
else:
print("Stepping not found")
else:
print("Project name not found")
if-else不需要多层结构。这是一个修改。我还使用os.path.join()比字符串操作更适合处理路径:
import os, shutil
working_dir = os.path.join("C:/", "path")
os.chdir(working_dir)
def main():
lvl1 = ['Typ','GFP2']
lvl2 = ['A0','A1']
# lvl3 = ['SCAN','MBIST']
project = input("Enter project: ")
if project not in lvl1:
print("Project name not found")
return
stepping = input("Enter Stepping: ")
if stepping not in lvl2:
print("Stepping not found")
return
thirdlvl = input("Enter SCAN/MBIST: ")
src = os.path.join(project, stepping, thirdlvl)
print("src", src)
if not os.path.exists(src):
print("Src not exists")
main()
os.listdir()您甚至可以通过为您列出所有子文件夹来进一步自动化该过程。
import os, shutil
working_dir = os.path.join("C:/", "path")
os.chdir(working_dir)
def main():
project = input("Enter project: ")
lvl1 = os.listdir(working_dir) # list all the directories under the working directory.
if project not in lvl1:
print("Project name not found")
return # if you want to exit when not finding the project folder.
stepping = input("Enter Stepping: ") # list all the directories under the project directory.
lvl2 = os.listdir(os.path.join(working_dir, project))
if stepping not in lvl2:
print("Stepping not found")
return # if you want to exit when not finding the stepping folder.
thirdlvl = input("Enter SCAN/MBIST: ")
src = os.path.join(project, stepping, thirdlvl)
print("src", src)
if not os.path.exists(src):
print("Src not exists")
main()
添加回答
举报