2016-04-16 24 views
-1

我正在寫python腳本來從dir中取出一個一個的文件,並且如果它的mimetype不是JSON,那麼就得到它mimetype然後我想忽略它。請參閱下面我的腳本我怎麼能從python中沒有文件中過濾掉mimetype JSON

for filepath in files: 
    filename = os.path.basename(filepath) 

    mimetype = mimetypes.guess_type(filepath, strict=False) //here i want to filter out only JSON file and ignore other one 

    version = "0" 
    checksum = "0" 
    fileext = os.path.splitext(filename)[1].lower()  
    # get raw file data 
    with open(filepath, "rb") as fr: 
     filedata = fr.read() 

    oldfilesize = len(filedata) 

見我在上面的代碼註釋。任何決議的一部分???

+0

您不能真正「獲取文件的mimetype」,因爲這不是系統維護的元數據。您可以嘗試通過文件擴展名來識別JSON文檔(查找'.json'),但通過檢查很難識別JSON文件。 – larsks

回答

1

你可以嘗試這樣的事:

for filepath in files: 
    filename = os.path.basename(filepath) 

    mimetype = mimetypes.guess_type(filepath, strict=False) 
    if mimetype != ('application/json', None): 
    with open(filepath) as f: 
     try: 
      json.load(f) 
     except ValueError: 
      # It's not json 
      continue 
    # do stuff 

但如果有大量的文件,這可能是低效的,和/或它們很大。

1

好,mimetypes不會幫助,因爲.json文件的MIME類型application/json固有的文件元數據。而不是用它來爲要處理它的人提供文件類型信息,例如在HTTP響應頭中的Content-Type: application/json告訴客戶端它是JSON。

無論如何,解決方案可能是如下,

import json 
with open("filename", "rt") as f: 
    try: 
     d = json.load(f) # no need to name it if you are just checking 
    except JSONDecodeError: 
     # handle it or just pass 
    else: 
     # Got a json file, do whatever