我需要在Windows上的Python中导入CSV文件。我的文件是由';'界定的并具有带有非英语符号和逗号(',')的字符串。
我已经阅读了帖子:
使用Python
将CSV文件导入SQLite3数据库表中python导入CSV
我运行时:
with open('d:/trade/test.csv', 'r') as f1:
reader1 = csv.reader(f1)
your_list1 = list(reader1)
我有一个问题:逗号更改为' - '符号。
我尝试时:
df = pandas.read_csv(csvfile)
我有错误:
pandas.io.common.cparsererror:错误令牌数据。C错误:第13行中的预期1个字段,SAW 2。
请帮忙。我更喜欢使用熊猫,因为代码较短,而不列出CSV文件中的所有字段名称。
我知道可能有暂时更换逗号的工作。不过,我想通过某些参数将其解决到熊猫。
pandas 解决方案 - 与Regex隔板[;,]
一起使用read_csv
。您需要添加engine='python'
,因为警告:
parserwarning:落回" python"引擎,因为" c"引擎不支持正则分离器(分隔符> 1个char,与" s "不同,将其解释为Regex);您可以通过指定引擎='Python'。
避免此警告。
import pandas as pd
import io
temp=u"""a;b;c
1;1,8
1;2,1
1;3,6
1;4,3
1;5,7
"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp), sep="[;,]", engine='python')
print (df)
a b c
0 1 1 8
1 1 2 1
2 1 3 6
3 1 4 3
4 1 5 7
pandas文档说明参数:
pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html
sep : str, default ‘,’
Delimiter to use. If sep is None, will try to automatically determine this.
pandas没有解析我的文件由 ;
界定,因为默认值未用于自动的 None
,而是 ,
。将sep
参数设置添加到;
的pandas
修复了问题。
除非您的CSV文件被打破,否则您可以尝试使csv
猜测您的格式。
import csv
with open('d:/trade/test.csv', 'r') as f1:
dialect = csv.Sniffer().sniff(f1.read(1024))
f1.seek(0)
r = csv.reader(f1, dialect=dialect)
for row in r:
print(row)
尝试指定编码,您将需要找出一个正在尝试读取的文件的编码。
我在此示例中使用了ASCII,但可能会有所不同。
df = pd.read_csv(fname, encoding='ascii')
避免在代码中的警告中
parserwarning:落回" python"引擎,因为" c"引擎不支持正则分离器(分隔符> 1个char,与" s "不同,将其解释为Regex);您可以通过指定引擎='Python'
来避免此警告
使用read_csv
功能内部的属性名称。检查两个情况下的示例以及不会出现的示例。
发出警告的代码:
selEncoding = "ISO-8859–1"
dfCovid19DS = pd.read_csv(dsSrcPath, selEncoding)
无警告的代码:
selEncoding = "ISO-8859–1"
dfCovid19DS = pd.read_csv(dsSrcPath, encoding = selEncoding)