def is_file_downloaded(filepath, stability_time=3, check_interval=1):
# Returns True if the file exists and its size doesn't change for stability_time seconds
if not os.path.exists(filepath):
return False
previous_size = -1
stable_time = 0
while stable_time < stability_time:
try:
current_size = os.path.getsize(filepath)
if previous_size == current_size:
stable_time += check_interval
else:
stable_time = 0
previous_size = current_size
except OSError:
# File does not exist yet
stable_time = 0
time.sleep(check_interval)
return True
Get the list of month names in lowercase
code
month_names = [m.lower() for m in calendar.month_name]
# Construct the expected filename based on the date format mentioned
file_name = a_date.strftime('%b %d, %Y.pdf') # e.g., Apr 03, 1926.pdf
file_path = os.path.join('/home/tom/Downloads', file_name)
print('Waiting for download to complete...')
while not is_file_downloaded(file_path, stability_time=3, check_interval=1):
if timeout_monitor.is_timeout():
print("Timeout occurred, restarting the loop with a_date:", a_date)
raise Exception("Timeout")
print('Download not finished yet...')
time.sleep(1)
# Check if there is any file in the download folder that matches the expected pattern
for f in os.listdir('/home/tom/Downloads'):
# Split the file name into parts
parts = f.split()
# Check if the first part is a valid month name or a substring of it
if any(parts[0].lower().startswith(m) for m in month_names):
# Check if the rest of the parts match the expected pattern
if re.match(r'(\d{2}), (\d{4})\.pdf', ' '.join(parts[1:])):
# Rename the file to the expected file name
os.rename(os.path.join('/home/tom/Downloads', f), file_path)
print('File renamed to', file_name)
break
print('Download finished!')
Above you have a method from my script and its implementation in the main() method of the same script.
A couple of days ago I asked my friend to alter the script in such a way as to make possible downloading the files that have
different strings representing the name of the month in the name of the downloaded file. I had to ask him for it, because
the site that I am downloading the files from has a proprietary app that controls the names of the files to download,
which means that I can't change their names when writing them to my disk, which would be the easiest and the most
obvious option. Unfortunately the files that the scrip has to download started to have unpredictable month names
in them, so I asked the friend for help. Unfortunately once again, the solution that he came up with doesn't work, and he
doesn't have the time right now to troubleshoot or better to fix the script for. Would you help me do just that?
I would really appreciate your help. :-)
Assistant
Here is how I would modify the script to make it more robust to handle files with varying month name strings:
Create a dict mapping month numbers to all possible month name variants:
When checking downloaded files, match any valid month name variant:
python
for filename in os.listdir():
parts = filename.split()
if parts[0].lower() in MONTH_NAMES[month_num]:
if re.match(f"({'|'.join(MONTH_NAMES[month_num])}) (\d{{2}}), (\d{{4}})\.pdf", filename):
# rename file
Handle potential errors from invalid date formats
This makes the script much more robust by:
Allowing any month name variant from the predefined list
Matching on month number rather than exact name string
Adding validation/error handling
Let me know if any part needs more explanation! I'm happy to help troubleshoot further.