To get the last file from a folder you can use metadata data de modificação
, the latest downloaded file is the one that has the most recent modification date

get the path
of the downloads folder
you can get folder path downloads on both linux and windows using the code below:
def get_download_path():
"""Returns the default downloads path for linux or windows"""
if os.name == 'nt':
import winreg
sub_key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'
downloads_guid = '{374DE290-123F-4565-9164-39C4925E467B}'
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, sub_key) as key:
location = winreg.QueryValueEx(key, downloads_guid)[0]
return location
return os.path.join(os.path.expanduser('~'), 'downloads')
Get the last file
Now that we have the download folder path, we have to get the path of each file inside it using lib glob
, read the modification date of each file using the os.path.getmtime()
and take the file that has the largest.
def get_latest_file_path(path):
"""return the more recent file in a path"""
file_paths = glob.glob(f'{path}/*') # obtem o path de cada arquivo na pasta
all_files_modification_time = [ os.path.getmtime(path) for path in file_paths ] # Obtem o modification time de cada arquivo
latest_file_index = all_files_modification_time.index(max(all_files_modification_time)) # obtem o index do maior deles, o arquivo mais recente
return file_paths[latest_file_index]
after this just open the file using the returned path
complete code below:
import os, glob
def get_download_path():
"""Returns the default downloads path for linux or windows"""
if os.name == 'nt':
import winreg
sub_key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'
downloads_guid = '{374DE290-123F-4565-9164-39C4925E467B}'
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, sub_key) as key:
location = winreg.QueryValueEx(key, downloads_guid)[0]
return location
return os.path.join(os.path.expanduser('~'), 'downloads')
def get_latest_file_path(path):
"""return the latest file in a path"""
file_paths = glob.glob(f'{path}/*')
all_files_modification_time = [ os.path.getmtime(path) for path in file_paths ]
latest_file_index = all_files_modification_time.index(max(all_files_modification_time))
return file_paths[latest_file_index]
downloads_path = get_download_path()
latest_file_path = get_latest_file_path(downloads_path)
with open(latest_file_path, 'r') as file:
pass
# seu código ...
The same can be used with the library
os
.files = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]
. Although the command is longer, there is no need to load another library.– Paulo Marques
vdd at this point you are right
– Jasar Orion
glob.glob can consume a lot of memory, the best is to use glob.iglob, the one that uses a iterator. A response I formulated dedicated to this: How to check which latest file in a Python folder?
– Guilherme Nascimento