使用Python检查文件是否为CSV格式 [英] Check if file has a CSV format with Python

查看:168
本文介绍了使用Python检查文件是否为CSV格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以提供有效的方法来检查文件是否有使用Python的CSV格式?

Could someone provide an effective way to check if a file has CSV format using Python ?

推荐答案

以下,但只是因为您从 csv中获得了一个方言.Sniffer 确实不足以保证您拥有有效的CSV文档。

You could try something like the following, but just because you get a dialect back from csv.Sniffer really won't be sufficient for guaranteeing you have a valid CSV document.

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

这篇关于使用Python检查文件是否为CSV格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆