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
Sure, I'd be happy to help.
It appears that the main complication lies in the variable month names in the file. As I can understand, the filenames were expected to follow the format '%b %d, %Y.pdf' (e.g., 'Apr 03, 1926.pdf'), but they now include different month names.
If the month names are all valid (i.e., they're not misspelled or abbreviated in a non-standard way), you could improve the current script to handle these different formats. Here's a revised version of your loop that checks the downloaded files:
python
import re, os, calendar
# Get the list of month names in lowercase
month_names = [m.lower() for m in calendar.month_name if m]
# Check if there is any file in the download folder that matches the expected pattern
for f in os.listdir('/home/tom/Downloads'):
parts = f.split()
# Check if the first part is a valid month name
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:])):
# Construct the expected filename based on the date format mentioned
expected_file_name = a_date.strftime('%b %d, %Y.pdf') # e.g., Apr 03, 1926.pdf
expected_file_path = os.path.join('/home/tom/Downloads', expected_file_name)
# Rename the file to the expected file name
os.rename(os.path.join('/home/tom/Downloads', f), expected_file_path)
print('File renamed to', expected_file_name)
break
This script updates your loop that checks for downloaded files. It first splits the filename into parts, checks if the first part (presumably the month name) matches any valid month name by using the startswith method (so it can handle abbreviated as well as full month names) and then checks if the rest of the filename matches the expected pattern. If both checks pass, it renames the file to the desired format.
Please note that this won't handle misspelled month names or similar deviations from the norm. If the deviation isn't consistent, we might not be able to design a generic solution. Also remember to double-check the correct handling of upper/lower case in filenames based on your operating system. and consider cases and errors that can occur when multiple files have the same or similar names.