检查文件是否具有Python的CSV格式

Joe*_*oe 20 python csv

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

got*_*nes 29

您可以尝试类似下面的内容,但仅仅因为您从中获得方言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
Run Code Online (Sandbox Code Playgroud)

  • *“......不足以保证......”*:是的。在没有提供方言的情况下,我将 .ZIP 检测为有效的 CSV,以 @ 作为分隔符 (4认同)

Dou*_*der 1

Python 有一个csv 模块,因此您可以尝试在各种不同的方言下解析它。