查找所有可能的循环-函数尝试

问题描述 投票:0回答:1

我编写了代码,现在我遇到的问题是代码仅找到第一个值(例如,只有[[img,我们也有img2,但它转到另一张图片),并且仅复制一个,但我们有2种可能性。

for i in df_list: img = (filepath + i + ".jpg") img2 = (filepath + i + "-1" + ".jpg") img3 = (filepath + i + "-2" ".jpg") img4 = (filepath + i + "-3" + ".jpg") img5 = (filepath + i + "-4" + ".jpg") img6 = (filepath + i + " -5" + ".jpg") try: shutil.copy(img, newpath, follow_symlinks=True) except: try: shutil.copy(img6, newpath, follow_symlinks=True) except: try: shutil.copy(img2, newpath, follow_symlinks=True) except: try: shutil.copy(img3, newpath, follow_symlinks=True) except: try: shutil.copy(img4, newpath, follow_symlinks=True) except: try: shutil.copy(img5, newpath, follow_symlinks=True) except: with open("C:/Users/"+user+"/Desktop/J/"+datum+"/"+"Napake.txt", "a") as text_file: print("Slika za ident {} ne obstaja.\n".format(i), file=text_file)
我需要帮助,谢谢您的回答。    
python loops try-catch shutil except
1个回答
0
投票
除了复制尝试,您可以循环遍历文件编号并尝试复制每个文件。并在有异常的情况下显示错误。

save_path = "C:/Users/" + user + "/Desktop/J/" + datum + "/" + "Napake.txt" for folder in df_list: for index in range(6): if index == 0: img = filepath + folder + ".jpg" else: img = f"{filepath}{folder}-{index}.jpg" try: shutil.copy(img6, newpath, follow_symlinks=True) with open(save_path, "a") as text_file: text_file.write(f"Slika za ident {folder}-{i} ne obstaja.\n") except Exception as e: print('could not copy file') print(e)

我也建议您查看this answer,以了解如何复制目录中的所有文件。    
© www.soinside.com 2019 - 2024. All rights reserved.