Last active
March 26, 2022 15:13
-
-
Save diegoquintanav/f10fd2dbbcb4708a8fa9282903336bb0 to your computer and use it in GitHub Desktop.
Move downloaded files to another folder using selenium
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pathlib import Path | |
import time | |
# adapted from https://stackoverflow.com/questions/23896625/how-to-change-default-download-folder-while-webdriver-is-running | |
def move_to_download_folder( | |
download_dir: Path, | |
new_destination_dir: Path, | |
lookup_str: str, | |
wait_seconds: int = 5, | |
max_tries: int = 3, | |
): | |
if download_dir in new_destination_dir.parents: | |
raise ValueError("new_destination should not be inside download_dir, otherwise data will be moved around recursively.") | |
# initialization | |
got_file = False | |
tries = 0 | |
# grab current file name. | |
while not got_file: | |
matched_files: list[Path] = list(download_dir.glob(lookup_str)) | |
if not matched_files: | |
if tries == max_tries: | |
print("Maximum number of tries reached. File was not found.") | |
break | |
else: | |
print(f"No file has been found. Perhaps it does not exist or it has not finished downloading yet. Waiting {wait_seconds} seconds to try again...") | |
tries += 1 | |
time.sleep(wait_seconds) | |
continue | |
else: | |
print(f"Matched {len(matched_files)} files.") | |
got_file = True | |
# create dest dir if it does not exist | |
new_destination_dir.mkdir(exist_ok=True, parents=True) | |
# Create new file name | |
for file in matched_files: | |
filename = file.name # file.ext | |
new_file_destination = new_destination_dir.joinpath(filename) # new_dir/file.ext | |
print(f"Moving {file} to {new_file_destination}.") | |
file.rename(new_file_destination) # mv current_dir/file.ext new_dir/file.ext | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
while
is bad, replace for afor
loop if you can.