Python 判断 Word 文档格式 (doc 或 docx)
可以使用 Python 的 os 模块和 re 模块来判断 Word 文档的格式,具体代码如下:
import os
import re
def check_format(file_path):
'判断 Word 文档的格式,返回 doc 或 docx'
file_name = os.path.basename(file_path)
if re.match(r'.*\.doc$', file_name):
return 'doc'
elif re.match(r'.*\.docx$', file_name):
return 'docx'
else:
return None
# 测试代码
file_path = 'test.doc'
format = check_format(file_path)
print(format) # 输出 doc
file_path = 'test.docx'
format = check_format(file_path)
print(format) # 输出 docx
上述代码中,check_format() 函数接收一个 Word 文档的路径,使用 os 模块和 re 模块来判断文档的格式。如果文档路径中包含 '.doc' 或 '.docx' 后缀,则认为是相应格式的文档,否则返回 None。
原文地址: https://www.cveoy.top/t/topic/nChz 著作权归作者所有。请勿转载和采集!