确定文件是 "more likely" json 还是 csv

Determine if a file is "more likely" json or csv

我有一些带有通用扩展名的文件,例如 "txt" 或者根本没有扩展名。我试图以非常快的方式确定文件是 json 还是 csv。我想过使用 magic 模块,但它对我想要做的事情不起作用。例如:

>>> import magic
>>> magic.from_file('my_json_file.txt')
'ASCII text, with very long lines, with no line terminators'

是否有更好的方法来确定某些内容是 json 还是 csv?我无法加载整个文件,我想以非常快的方式确定它。这里有什么好的解决方案?

您可以检查文件是否以 {[ 开头以确定它是否是 JSON,并且您可以加载前两行 csv.reader 和查看两行的列数是否相同,判断是否为CSV。

import csv
with open('file') as f:
    if f.read(1) in '{[':
        print('likely JSON')
    else:
        f.seek(0)
        reader = csv.reader(f)
        try:
            if len(next(reader)) == len(next(reader)) > 1:
                print('likely CSV')
        except StopIteration:
            pass

您可以使用 try/catch "technique" 尝试将数据解析为 JSON 对象。从字符串加载无效格式的 JSON 时,它会引发一个 ValueError ,您可以根据需要捕获和处理它:

>>> import json
>>> s1 = '{"test": 123, "a": [{"b": 32}]}'
>>> json.loads(s1)

如果有效,什么都不发生,如果无效:

>>> import json
>>> s2 = '1;2;3;4'
>>> json.loads(s2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 369, in decode
    raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 2 - line 1 column 8 (char 1 - 7)

所以你可以构建一个函数如下:

import json

def check_format(filedata):
    try:
        json.loads(filedata)
        return 'JSON'
    except ValueError:
        return 'CSV'

>>> check_format('{"test": 123, "a": [{"b": 32}]}')
'JSON'
>>> check_format('1;2;3;4')
'CSV'