python - Python - 防止以特定格式打开文件
问题描述
在代码执行期间,我有什么办法可以防止用户以 .pdf 格式打开文件?我的代码在循环中打开/保存多个文件,打开一个新文件可能会导致错误。操作系统是 Windows。谢谢
解决方案
使其成为打开文件的功能
检查扩展是否允许扩展然后
读
否则返回或可以引发自定义异常
from os import path
def openfile(filename):
dont_read_extensions = [".pdf", ".jpg"]
extension = path.splitext(filename)[1]
if extension in dont_read_extensions:
return #or you can raise custom exception
else:
with open(filename,"r") as f:
#do file operations
return # you can return with result