python3扫描文件 读取文件

60 阅读1分钟

这个应用扫描前端传参数的文件夹下的列表 等信息

这里做到了 dev 时是脚本所在的文件 打包后是exe 同级目录

打包时可以开启参数进行调试测试



def scan_folder(path):
    files_list = []
    for root, directories, files in os.walk(path):
        for filename in files:
            file_path = os.path.join(root, filename)
            file_info = {
                'filename': filename,
                'path': file_path,
                'size': os.path.getsize(file_path),
                'last_modified': os.path.getmtime(file_path),
                'file_type': os.path.splitext(file_path)[1]  # 获取文件类型
            }
            files_list.append(file_info)
    return files_list

@app.route('/api/allfiles')
def get_allfiles_list():
    print(sys.argv[0])
    folder_path = os.path.join(pathlib.Path(sys.argv[0]).parent, './')  # 获取exe所在目录并拼接文件夹名
    print(folder_path)
    files_list = scan_folder(folder_path)
    return jsonify({"code":200,'message': "success",'data': files_list})

@app_main.route('/api/files', methods=['POST'])
def get_files_list(): 
    full_path = os.path.join(pathlib.Path(sys.argv[0]).parent, request.json.get('path'))
    if os.path.exists(full_path) and os.path.isdir(full_path):
        files =  os.listdir(full_path)
        files_list = []
        for filename in files:
            file_path = os.path.join(full_path, filename)
            file_info = {
                'filename': filename,
                'path': file_path,
                'size': os.path.getsize(file_path),
                'last_modified': os.path.getmtime(file_path),
                 'isFile': os.path.isfile(file_path),
                'file_type': os.path.splitext(file_path)[1]  # 获取文件类型
            }
            files_list.append(file_info)
        
        return jsonify({"code":200,'message': "success",'data': files_list})
    else:
        return jsonify({"code":400,'message': "Invalid path or path is not a directory.",'data': ''}) 

@app_main.route('/api/file', methods=['POST'])
def read_file(): 
    path = request.json.get('path')
    if not path:
        return 'Path parameter is missing', 400 
    full_path = os.path.join(pathlib.Path(sys.argv[0]).parent, path) 
    if os.path.exists(full_path) and os.path.isfile(full_path):
        with open(full_path, 'r') as file:
            file_content = file.read()
        return jsonify({"code":200,'message': "success",'data': file_content})
    else:
        return 'File not found or path is not a file', 404