如何打开一个 .pdf 文件,只知道它的部分名称

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

我的文件夹中有 pdf 文件,我需要通过只知道文件编号来打开文件。 名称是这样的:“TK20141 - 公司名称”,所以我需要只知道“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)])

这段代码给出了这个错误:

['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

您正在将列表作为参数传递给 xdg-open。如果您只想打开列表中的第一个 PDF,可以尝试使用:

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

编辑:

阅读您的评论后,我发现您需要提供 PDF 文件的完整路径。试试这个:

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

您可以使用 glob.glob() 使用通配符查找文件,而不是列出所有文件,然后通过文件列表查找所需的文件。

另外Windows平台没有xdg-open,用os.startfile()代替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])