Grab last file that entered in "Downloads" folder

Asked

Viewed 83 times

3

How can I open the last file that was downloaded in the folder "Downloads" with Python?

I saw several options with the libs os.path and os.walk but none of them makes it possible to take the last file that entered the directory.

On the Colab (Google) platform and using Linux, I saw a person doing:

!ls -1t *.csv

2 answers

4

you can use the function glob python in this way:

import glob
import os.path

folder_path = r'C:\Users\MasterRoot\Desktop\Test'
file_type = '\*csv' # se nao quiser filtrar por extenção deixe apenas *
files = glob.glob(folder_path + file_type)
max_file = max(files, key=os.path.getctime)

print (max_file)

it will return you the last file added to this directory.

  • 3

    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.

  • vdd at this point you are right

  • 1

    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?

0

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

O último arquivo tem a data de modificação mais recente

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 ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.