我的檔案夾中有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
uj5u.com熱心網友回復:
您可以使用glob.glob()通配符來查找檔案,而不是列出所有檔案,然后通過檔案串列查找所需的檔案。
xdg-open在 Windows 平臺上也沒有,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])
uj5u.com熱心網友回復:
您正在將串列作為引數傳遞給 xdg-open。如果您只想打開串列中的第一個 PDF,可以嘗試:
subprocess.call(["xdg-open", otsi(otsitav)[0])
編輯:
閱讀您的評論后,我發現您需要提供 PDF 檔案的完整路徑。嘗試這個:
subprocess.call(["xdg-open", 'C:/Users/ASUS/Desktop/Proov/' otsi(otsitav)[0])
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/430792.html
