【问题标题】:How to select only .json file using python 3.7如何使用 python 3.7 仅选择 .json 文件
【发布时间】:2019-08-30 06:41:50
【问题描述】:

我正在尝试仅选择 .json 文件。我可以选择 .json 文件,但无法验证该文件。

我正在使用带有 tkinter 的 python 3.7.3。到目前为止,我已经实现了以下目标

from tkinter import *
import tkinter as tk
from tkinter import ttk
import os
import json
import csv
from tkinter.filedialog import askopenfilename

def JsonFormat():
    name = askopenfilename(initialdir="../Path/For/JSON_file",
                           filetypes=(("Json File", "*.json"), ("All Files", "*.*")),
                           title="Choose a file."
                           )
    json_string = None
    try:
        with open(name, 'r', encoding='utf8') as f:
            json_string = f.read()
            parsed_json = json.loads(json_string)
            formatted_json = json.dumps(parsed_json, indent = 4,sort_keys=True)
            with open(name, 'w', encoding='utf8') as f:
                f.write(formatted_json)
            messagebox.showinfo("Information","JSON file formatted")
    except Exception:
        messagebox.showerror("Error Message", 'File not selected')

我只想知道如何验证我正在阅读的文件是 .json 格式而不是任何其他格式。提前致谢。

【问题讨论】:

  • "无法验证文件。" 是什么意思?它是如何失败的?你有错误吗?它认为非json文件是json吗?它认为json文件不是json吗?

标签: python-3.x file tkinter


【解决方案1】:

为什么在需要的时候只添加所有类型的json

name = askopenfilename(initialdir="../Path/For/JSON_file",
                           filetypes=(("Json File", "*.json"),),
                           title="Choose a file."
                           )

使用列表:

name = askopenfilename(initialdir="../Path/For/JSON_file",
                           filetypes=[("Json File", "*.json")],
                           title="Choose a file."
                           )

但无法验证文件:您失败的地方...请分享错误

如果我没有得到你,我很抱歉...n少回购所以不能评论:(

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-15
    • 2015-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多