Reputation: 3169
I have created a Python script that needs a file to be present in a directory. This file is for example downloaded from a browser (for example with Selenium). The workflow that I've imaginated is the following:
Even if the file is present in the directory, the loops is executed 10 times instead of being broken.
file_was_downloaded = False
for u in range(10):
click(Link('download the file in the directory'))
time.sleep(10)
files = os.listdir('C:/Users/XYZ/Downloads/')
for f in files:
if f.startswith("the_file.jpg") and not f.endswith(".crdownload"): # ".crdownload" if a suffix appended to the name of the file by Google Chromium/Chrome if it's not completely downloaded
file_was_downloaded = True
break
if not file_was_downloaded:
print(datetime.datetime.now() + " - The file may not be present in the directory.\n")
exit(-1)
# Below this line, we can use the file.
You can remove the line click
and replace it by yourself adding the wanted file in the directory when you want, while the script is running. You will see that the loop will continue to iterate even if the file is in the directory. That's the problem and I don't know why it behaves like this.
When the file is detected as "present" in the directory, the loop breaks.
The loop continues to iterate.
Upvotes: 1
Views: 745
Reputation: 91
Try something like this:
import time
for i in range(10):
'''your donwload code'''
try:
file = open("yourfile.jpg")
break
except:
time.sleep(10)
Upvotes: 0
Reputation: 384
Your break statement only breaks the "for f in files" loop. add another if in the "for u in range" loop:
if file_was_downloaded:
break
Upvotes: 2