Python - 如何找到精确的扩展名?
我正在尝试遍历一个文件夹,里面有几个文件,想找到扩展名为 .doc
的文件。
我确实使用了 .endswith('.doc')
这个函数,但在我的情况下,它也会把 .docx
文件也算进去。有没有什么正则表达式或者其他方法可以用呢?
编辑:好的,我的问题是,我在循环中查找 ".doc" 文件,如果找到了,就会把文本提取到一个变量中,然后使用 win32com 函数打印出来。当我把程序放到一个同时包含 ".doc" 和 ".docx" 文件的文件夹时,我遇到了一个错误,提示如下:
Traceback (most recent call last):
File "C:\Users\IdaLim\Desktop\MyTestCode\FileIO.py", line 88, in <module>
doc = app.Documents.Open(fullpath)
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 522, in
__getattr__
raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: Word.Application.Documents
根据我对 COM 函数的经验和了解,它也在解析 ".docx" 文件,这就是为什么没有 ".docx" 文件的 "Word.Application.Documents"。这也解释了那个错误。
所以当我把 ".doc" 文件单独放到另一个文件夹里(也就是没有 .docx 文件的地方),循环和程序就完全正常了。它能打印出文件的内容,然后就结束了。
我的代码摘录:
import win32com.client
import os
rootdir ='C:\Users\IdaLim\Desktop\docs'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
fullpath = os.path.join(*[subdir, file])
if file.endswith('.doc'):
app = win32com.client.Dispatch('Word.Application')
doc = app.Documents.Open(fullpath)
print doc.Content.Text
app.Quit()
2 个回答
我不知道os.walk()对象的具体结构,不过假设你有一个包含文件名的字符串数组,你可以用这个正则表达式来筛选它们:
import re
array = ['file1.doc', 'file2.docx']
regexp = "\.doc$"
for e in array:
if re.search(regexp, e, re.I):
print 'True'
else:
print 'False'
结果:
True
False
(已编辑。请见下方原始回答。)
这里真正的问题似乎和算法或者系统的其他部分有关(根据评论提到重启会改变一些东西),因为 str.endswith()
和 Path.suffix
应该在这里给出相同的结果。
之前的内容(不是真正的问题)
最简单且最可靠的解决方案是使用 pathlib
模块。如果你使用的是 Python 3.4 或更新版本,它已经预装了;如果不是,可以用 pip
或 easy_install
来安装。然后你可以这样处理你的路径:
import win32com.client
import os
import pathlib
rootdir ='C:\Users\IdaLim\Desktop\docs'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
fullpath = pathlib.Path(subdir, file)
if fullpath.suffix == '.doc':
app = win32com.client.Dispatch('Word.Application')
doc = app.Documents.Open(str(fullpath))
print doc.Content.Text
app.Quit()
suffix
属性使用起来简单且可靠,可以帮你得到想要的结果。想了解更多细节,可以查看 pathlib
模块在 3.4 版本的文档,点击这里。