我是 python
的新手,刚刚安装了 Eric6
我想搜索一个文件夹(和所有子目录)以打印任何文件的文件名.pdf
的扩展我有这个作为我的语法,但它错误地说
The debugged program raised the exception unhandled FileNotFoundError
"[WinError 3] The system can not find the path specified 'C:'"
File: C:\Users\pcuser\EricDocs\Test.py, Line: 6
这是我要执行的语法:
import os
results = []
testdir = "C:\Test"
for folder in testdir:
for f in os.listdir(folder):
if f.endswith('.pdf'):
results.append(f)
print (results)
最佳答案
使用 glob
模块。
The glob module finds all the pathnames matching a specified pattern
import glob, os
parent_dir = 'path/to/dir'
for pdf_file in glob.glob(os.path.join(parent_dir, '*.pdf')):
print (pdf_file)
这将适用于 Windows 和 *nix 平台。
只需确保您的路径在 Windows 上完全转义,这对使用原始字符串很有用。
在您的情况下,这将是:
import glob, os
parent_dir = r"C:\Test"
for pdf_file in glob.glob(os.path.join(parent_dir, '*.pdf')):
print (pdf_file)
对于仅文件名列表(不是完整路径,根据您的评论),您可以这样做:
results = [os.path.basename(f) for f in glob.glob(os.path.join(parent_dir, '*.pdf')]
关于python - 打印文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35702996/