Python自动检测文件为csv或json并读取它

问题描述 投票:0回答:2

目的:

  1. Python 3函数应该能够读取jsoncsv文件并且必须返回json
  2. AutoDetect格式,我正在使用return json.load(fileObject)的try catch技巧
  3. 完全严格的函数与try catch语句

问题:它与json文件作为输入正常工作,但对于csv它显示空数组

任何更好的方法?

CSV文件:

Alpha,Beta,Gamma
1,2,3

JSON文件:

[
  {
    "Alpha": 1,
    "Beta": 2,
    "Gamma": 3
  }
]

码:

import csv
import json

def read_input_File(file_path):
    try:
        fileObject = open(file_path, 'rU')
        # check if it is json
        try:
            return json.load(fileObject)
        except:
            # it is csv then
            reader = csv.DictReader(fileObject)
            # Parse the CSV into JSON
            out = json.dumps([row for row in reader])
            return out
    except IOError as e:
        raise SystemExit("I/O error(%s): %s", e.errno, e.strerror)

    finally:
        fileObject.close()
python python-3.x
2个回答
3
投票

我猜测json.load()调用消耗了文件。也许在fileObject.seek(0)召唤之前尝试csv.DictReader()


1
投票

我不认为使用try catch块是必要的。为了便于阅读,我会使用if else语句。

import json
import csv

def read_input_File(file_path):
    if file_path.endswith(".json"): return json.load(open(file_path,"r"))    
    elif file_path.endswith(".csv"): return json.dumps(list(csv.DictReader(open("prova.csv"))))
    else: raise ValueError("The file is not json nor cvs")
© www.soinside.com 2019 - 2024. All rights reserved.