我在Django Architecture中有这个utils.py文件:
def range_data(ip):
r = []
f = open(os.path.join(settings.PROJECT_ROOT, 'static', 'csv ',
'GeoIPCountryWhois.csv'))
for num,row in enumerate(csv.reader(f)):
if row[0] <= ip <= row[1]:
r.append([r[4]])
return r
else:
continue
return r
这里的ip参数只是IPv4地址,我使用的是开源的MAXMIND GeoIPCountrywhois.csv
文件。
GeopIOCountrywhois.csv
的一些首发内容:
"1.0.0.0","1.0.0.255","16777216","16777471","AU","Australia"
"1.0.1.0","1.0.3.255","16777472","16778239","CN","China"
"1.0.4.0","1.0.7.255","16778240","16779263","AU","Australia"
"1.0.8.0","1.0.15.255","16779264","16781311","CN","China"
"1.0.16.0","1.0.31.255","16781312","16785407","JP","Japan"
"1.0.32.0","1.0.63.255","16785408","16793599","CN","China"
"1.0.64.0","1.0.127.255","16793600","16809983","JP","Japan"
"1.0.128.0","1.0.255.255","16809984","16842751","TH","Thailand"
我也读过这个问题,但没有发现这么多可以理解。你能帮我解决一下这个错误吗?
根据我在utils中的方法,我正在检查方法参数IP
地址的国家名称。
答案 0 :(得分:14)
今天早些时候有类似的问题,一行中缺少一个结束引用,解决方法是指示reader
不对引号字符(quoting=csv.QUOTE_NONE
)执行特殊处理。
答案 1 :(得分:8)
您可以通过删除下面的换行来预处理csv。
import csv
content = open("GeoIPCountryWhois.csv", "r").read().replace('\r\n','\n')
with open("GeoIPCountryWhois2.csv", "w") as g:
g.write(content)
然后将GeoIPCountryWhois2用于csv阅读器。
使用lineterminator进行疯狂猜测可以解决您的问题
for num,row in enumerate(csv.reader(f,lineterminator='\n'))
答案 2 :(得分:3)
您必须以二进制文件打开文件:
def range_data(ip):
r = []
f = open(os.path.join(settings.PROJECT_ROOT, 'static', 'csv ',
'GeoIPCountryWhois.csv'), 'rb')
for num,row in enumerate(csv.reader(f)):
# Your things.
注意那里的'rb'
模式;否则文件可以使用本机行结尾打开,并且CSV阅读器不能很好地处理各种表单。当然, I 下载的GeoIPCountryWhois.csv
副本具有干净的\n
行结尾。
如果csvfile是一个文件对象,那么它必须在平台上以“b”标志打开,这会产生影响。
但是,如果您的csv文件已损坏,并且在意外的地方仍然包含意外的换行符,请使用此file
子类作为间隙措施:
class CleanlinesFile(file):
def next(self):
line = super(CleanlinesFile, self).next()
return line.replace('\r', '').replace('\n', '') + '\n'
此类保证在返回结果中的任何位置都不会有换行符,除非是最后一个字符(就像csv模块想要的那样)。使用它代替open
电话;在这种情况下,'rb'
模式修饰符变为可选:
def range_data(ip):
r = []
f = CleanlinesFile(os.path.join(settings.PROJECT_ROOT, 'static', 'csv ',
'GeoIPCountryWhois.csv'))
for num,row in enumerate(csv.reader(f)):
# Your things.