I want to read 2 different types of CSV-files:
我想阅读2种不同类型的CSV文件:
- one with a
','
as delimiter - 一个带有','作为分隔符
- one with a
';'
as delimiter - 一个带';'作为分隔符
I tried to check which delimiter I'm using by doing:
我试着通过这样做来检查我正在使用哪个分隔符:
dialect = csv.Sniffer().sniff(csvfile, [',', ';'])
data = csv.reader(csvfile, dialect)
but then I get the TypeError : expected string or buffer
.
但后来我得到了TypeError:期望的字符串或缓冲区。
If I do this, it works, but then I don't know when to use what delimiter.
如果我这样做,它可以工作,但后来我不知道何时使用什么分隔符。
data = csv.reader(csvfile, delimiter = ",")
data = csv.reader(csvfile, delimiter = ";")
Can someone help me please?
有人能帮助我吗?
1 个解决方案
#1
16
Sniffer expects a sample string, not a file. All you should need to do is:
Sniffer需要一个示例字符串,而不是文件。你需要做的就是:
dialect = csv.Sniffer().sniff(csvfile.readline(), [',',';'])
csvfile.seek(0)
data = csv.reader(csvfile, dialect)
The seek is important, because you are moving your current position in the file with the readline command, and you need to reset back to the beginning of the file. Otherwise you lose data.
搜索很重要,因为您使用readline命令在文件中移动当前位置,并且需要重置回文件的开头。否则你会丢失数据。
#1
16
Sniffer expects a sample string, not a file. All you should need to do is:
Sniffer需要一个示例字符串,而不是文件。你需要做的就是:
dialect = csv.Sniffer().sniff(csvfile.readline(), [',',';'])
csvfile.seek(0)
data = csv.reader(csvfile, dialect)
The seek is important, because you are moving your current position in the file with the readline command, and you need to reset back to the beginning of the file. Otherwise you lose data.
搜索很重要,因为您使用readline命令在文件中移动当前位置,并且需要重置回文件的开头。否则你会丢失数据。