[英]how can i find the no.of files with a list of target extensions eg:.txt, .pdf etc and print it separately for current and sub directories using python
[英]how can i store only pdf file or filename from folder containing another files with different extensions (.doc, .txt, .html) in variable using python?
讓我們考慮桌面上的文件夾(Mandar 和 html)。 現在粘貼任何 pdf 文件並在 'html' 文件夾中將其命名為 'dell' 並在 'Mandar' 文件夾中創建 demo.py 文件。 現在根據需要創建一些 txt 文件(2-4),以便“html”文件夾包含一些 txt 文件和一個 pdf 文件。
import os
import PyPDF2 # install via 'pip install PyPDF2'
# Put location of your pdf file i.e. dell.pdf in 'location' variable
location = "C:/Users/Desktop/html/"
n = "dell.pdf"
path = os.path.join(location, n)
reader = PyPDF2.PdfReader(path)
pages = len(reader.pages)
print(f"The no. of pages in {n} is {pages}.")
現在運行程序,你會看到''沒有。 dell.pdf 中的頁面數為 NUM。'' //NUM 為否。 您的 pdf 頁數
現在讓我們考慮'html'文件夾總是只包含一個pdf文件,任何名稱可能是dell,可能是ecc,也可能是任何名稱。 我希望該變量“n”將這個 pdf 文件本身存儲為輸入,以便程序運行並顯示具有不同 pdf 文件名和 Num 的相同結果。
試一試標准庫中的glob
。 它會為您提供該目錄中所有匹配的 PDF 文件的列表。
import os
import PyPDF2
...
import glob
Location='C:/Users/Desktop/html/'
candidates = glob.glob(os.path.join(Location, '*.pdf'))
if len(candidates) == 0:
raise Exception('No PDFs found')
File=open(candidates[0],'rb')
...
您正在尋找通配符。 你可以用pathlib
做到這一點:
from pathlib import Path
root = Path(location)
pdf_files = root.glob("*.pdf")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.