I have folders in a directory named 2001,2002,2003,2004,2005. However when I iterate through them inside the 'for batch in batchno: print(batch)' It only prints the first one 2001. If I print the parameter "Batchno", it gives me all folders. IS there something breaking out of the loop that I am missing? I read that a return can break out of your loop, not sure if "return filename" is doing that.
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)
output:
2001
expected output:
2001,2002,2003,2004,2005
Absolutely! It's hitting your return at the end of the first iteration of the for loop
If I'm interpreting what you're attempting to do correctly, you can simply remove the return and your code should run fine
Yes, a return will end execution of a loop. Try accumulating your result values and return them together after the for
has completed.
Example using a list to accumulate the values
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
Edit:
In case you only need those values to call the makePdf
function you can also directly call the function inside the loop, without returning anything
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”,以便在第一次迭代结束时它将从函数中出来
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.