python 弹窗选择文件并判断文件是否被打开

详细代码

# -*- ecoding: utf-8 -*-
# @ModuleName: test002
# @Function: 
# @Author: darling
# @Time: 2022-06-01 13:46


import os
import re
import sys
import time
import tkinter as tk
from tkinter import filedialog

from loguru import logger

# 实例化
root = tk.Tk()
root.withdraw()

def exit_sys(msg):
    logger.info(msg)
    logger.info('程序退出··· ···')
    time.sleep(3)
    sys.exit()


# 判定文件是否打开
def fileIsOpen(filepath):
    # filepath = C:/Users/Administrator/Desktop/新用户创建.xlsx  #获取文件的目录
    filef = os.path.split(filepath)  # 文件路径和文件名拆开
    excelname = filef[-1]
    excelpath = filef[0]
    hidefilename = excelpath + r"/~$" + excelname  # 拼接出隐藏文件的文件路径
    if os.path.exists(hidefilename):
        return True
    else:
        return False


def exists_file(file_name):
    return os.path.exists(file_name)


def check_file_type(f_path):
    txt = re.compile(r'\.xlsx$')
    if txt.search(f_path) is None:
        # logger.info('只允许xlsx文件')
        exit_sys('文件格式格式不正确,只允许xlsx文件')
    if not exists_file(f_path):
        exit_sys(f_path + ' 文件不存在,请在当前目录检查必要文件')
    if fileIsOpen(f_path):
        exit_sys(f_path + ' 文件被占用,请关闭')

# 弹窗选择文件,并获取文件路径
def get_file_path():
    # 获取文件夹路径
    f_path = filedialog.askopenfilename()
    logger.info('获取的文件地址:{}', f_path)
    # 文件校验
    check_file_type(f_path)
    return f_path


if __name__ == '__main__':
    get_file_path()

posted @ 2022-06-01 01:59  darling331  阅读(589)  评论(0编辑  收藏  举报