[英]Code Breaks Out of Iteration - Only Printing First Item
我在名為 2001,2002,2003,2004,2005 的目錄中有文件夾。 但是,當我在 'for batch in batchno: print(batch)' 中遍歷它們時,它只打印第一個 2001。如果我打印參數“Batchno”,它會給我所有文件夾。 有什么東西打破了我遺漏的循環嗎? 我讀到 return 可以跳出你的循環,不確定“return filename”是否這樣做。
def getCOAFilePaths(batchno, pdkey):
for date in pdkey:
date = date
for batch in batchno:
print(batch)
filepath = f'\\\test/User/000/000/{date}/IMGCD/{batch}/'
abspth = os.path.abspath(filepath)
for row in os.listdir(filepath):
print(abspth+"\\"+row)
logging.info(abspth+"\\"+row)
return filepath
makePdf(filepath, r'C:\Users\TEST\COA\misc.fof')
def makePdf(filepath, SaveToDir):
os.chdir(filepath)
try:
for j in os.listdir(os.getcwd()):
os.chdir(filepath)
fname, fext= os.path.splitext(j)
newfilename = fname + ".pdf"
im = Image.open(fname + fext)
os.chdir(SaveToDir)
im.save(newfilename, "PDF", resolution=100.0)
except Image.UnidentifiedImageError:
print(f"{fname+fext} found. Skipping UnidentifiedImageError error because this library cannot open a .db file "
f"and convert it to pdf.")
makePdf(filepath, r'C:\Users\TEST\COA\misc.fof')
filepath = getCOAFilePaths(x1, x5)
輸出:
2001
預期輸出:
2001,2002,2003,2004,2005
絕對地! 它在 for 循環的第一次迭代結束時擊中了你的回報
如果我正在解釋您嘗試正確執行的操作,您只需刪除返回值,您的代碼應該可以正常運行
是的,返回將結束循環的執行。 嘗試累積您的結果值並在for
完成后將它們一起返回。
使用列表累積值的示例
filepaths = [] # Create an empty list
for batch in batchno:
print(batch)
filepath = f'\\\test/User/000/000/{date}/IMGCD/{batch}/'
abspth = os.path.abspath(filepath)
for row in os.listdir(filepath):
print(abspth+"\\"+row)
logging.info(abspth+"\\"+row)
filepaths.append(filepath) # Accumulate values here
return filepaths # Return the list once completed the loop
編輯:
如果您只需要這些值來調用makePdf
函數,您也可以直接在循環內調用該函數,而無需返回任何內容
for batch in batchno:
print(batch)
filepath = f'\\\test/User/000/000/{date}/IMGCD/{batch}/'
abspth = os.path.abspath(filepath)
for row in os.listdir(filepath):
print(abspth+"\\"+row)
logging.info(abspth+"\\"+row)
makePdf(filepath, r'C:\Users\TEST\COA\misc.fof')
您在 for 循環中使用了“return”,以便在第一次迭代結束時它將從函數中出來
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.