Search code examples
pythonhyperlinkoperating-systempathlib

Open files with one click using python


I made this code which shows the titles of files from my computer using os and pathlib.

import os
from pathlib import Path

class Buscador:
    def Busca():
        opcao = str(input('Por qual palavra deseja buscar o documento? '))
        for file in os.listdir("/home/paulo/Documentos"):
            if file.endswith(".pdf"):
                file_name = Path(file).stem
                if opcao in file_name:
                    print(os.path.join(file_name))
                    print(' ')

Buscador.Busca()

I'd like to complement it by leaving the titles clickable, like a link. Clicking on the title would open the file


Solution

  • If what you mean is you can click the path to open the file location from the output section, then this is done through your code editor or IDE.

    Edit: I made this code which will scan a certain directory on my PC for files, if the result is a file it will will print the path in the format

    C:\Users\John\Desktop\test.txt
    

    If you want to open the file(using Visual Studio Code), just ctrl+click the output and it will open the file in a new tab.

    The code:

    import os
    
    directory = r'path'    #The path to the folder containing the file
    
    for filename in os.listdir(directory):
        f = os.path.join(directory, filename)
        if os.path.isfile(f):
            print(f)