有没有人能够提供一种使用Python检查文件是否为CSV格式的有效方法?
有没有人能够提供一种使用Python检查文件是否为CSV格式的有效方法?
csv.Sniffer
获取方言并不能保证你拥有一个有效的CSV文档。csv_fileh = open(somefile, 'rb')
try:
dialect = csv.Sniffer().sniff(csv_fileh.read(1024))
# Perform various checks on the dialect (e.g., lineseparator,
# delimiter) to make sure it's sane
# Don't forget to reset the read position back to the start of
# the file before reading any entries.
csv_fileh.seek(0)
except csv.Error:
# File appears not to be in CSV format; move along
除了gotgenes的答案中提到的内容,我认为还需检查不应包含在CSV文件中的不可打印字符,这样可以获得良好的结果。
def is_csv(infile):
try:
with open(infile, newline='') as csvfile:
start = csvfile.read(4096)
# isprintable does not allow newlines, printable does not allow umlauts...
if not all([c in string.printable or c.isprintable() for c in start]):
return False
dialect = csv.Sniffer().sniff(start)
return True
except csv.Error:
# Could not get a csv dialect -> probably not a csv.
return False
尝试将其解析为CSV格式,看看是否会出错。