Home > Blockchain >  How to open a .pdf file, knowing only part of it's name
How to open a .pdf file, knowing only part of it's name

Time:02-22

I have pdf files inside a folder, I need to open a file by knowing only it's number. The names are like: "TK20141 - Company name", So I need to open the file by only knowing the "20141".

import os
import subprocess

def otsi(x):
    leitud = []
    arr = os.listdir('C:/Users/ASUS/Desktop/Proov')
    for i in range(len(arr)):
        if x in arr[i]:
            leitud.append(arr[i])
    return leitud

otsitav="33333"
print(otsi(otsitav))
subprocess.call(["xdg-open", otsi(otsitav)])

This code gives this error:

['TK33333 - Test.pdf']
Traceback (most recent call last):
  File "c:\Users\ASUS\Desktop\Pooleli olev töö\Märkmed\import os.py", line 14, in <module>
    subprocess.call(["xdg-open", otsi(otsitav)])
  File "C:\Users\ASUS\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 345, in call
    with Popen(*popenargs, **kwargs) as p:
  File "C:\Users\ASUS\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 966, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Users\ASUS\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 1375, in _execute_child
    args = list2cmdline(args)
  File "C:\Users\ASUS\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 561, in list2cmdline
    for arg in map(os.fsdecode, seq):
  File "C:\Users\ASUS\AppData\Local\Programs\Python\Python310\lib\os.py", line 822, in fsdecode
    filename = fspath(filename)  # Does type-checking of `filename`.
TypeError: expected str, bytes or os.PathLike object, not list

CodePudding user response:

You can use glob.glob() to find files using wildcard instead of listing all the files and then go through the file list to find the required files.

Also there is no xdg-open in Windows platform, use os.startfile() instead of subprocess.call().

import glob
import os

def otsi(x):
    return glob.glob(f'C:/Users/ASUS/Desktop/Proov/*{x}*.pdf')

otsitav="33333"
files = otsi(otsitav)
print(files)
if files:
    os.startfile(files[0])

CodePudding user response:

You are passing a list as a parameter to xdg-open. If you only want to open the first PDF in the list, maybe try with:

subprocess.call(["xdg-open", otsi(otsitav)[0])

EDIT:

After reading your comment, I see that you need to provide the full path to the PDF file. Try this:

subprocess.call(["xdg-open", 'C:/Users/ASUS/Desktop/Proov/'   otsi(otsitav)[0])
  • Related