How to programmatically guess whether a CSV file is comma or semicolon delimited

前端 未结 5 1815
滥情空心
滥情空心 2021-01-04 08:29

In most cases, CSV files are text files with records delimited by commas. However, sometimes these files will come semicolon delimited. (Excel will use semicolon delimiter

5条回答
  •  心在旅途
    2021-01-04 09:07

    Let's say you have the following in your csv:

    title,url,date,copyright,hdurl,explanation,media_type,service_version
    

    then you can use python's in-built CSV module as follows:

    import csv
    data = "title,url,date,copyright,hdurl,explanation,media_type,service_version"
    sn = csv.Sniffer()
    delimiter = sn.sniff(data).delimiter
    

    Printing the variable named delimiter will return ',' and this is the delimiter here. You can test by using some different delimiters.

提交回复
热议问题