在Python中读取csv文件时获取"换行符在字符串内"?

Ami*_*Pal 8 python csv django python-2.7

我在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
Run Code Online (Sandbox Code Playgroud)

这里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"
Run Code Online (Sandbox Code Playgroud)

我也读过这个问题,但没有发现这么多可以理解.你能帮我解决一下这个错误吗?

根据我在utils中的方法,我正在检查IP方法的paasing参数地址的国家名称.

Jim*_*edi 14

今天早些时候有类似的问题,一行中缺少一个结束引用,解决方法是指示reader不对引号字符(quoting=csv.QUOTE_NONE)执行特殊处理.


shi*_*iva 8

  1. 您可以通过删除下面的换行来预处理csv.

    import csv
    
    content = open("GeoIPCountryWhois.csv", "r").read().replace('\r\n','\n')
    
    with open("GeoIPCountryWhois2.csv", "w") as g:
        g.write(content)
    
    Run Code Online (Sandbox Code Playgroud)

    然后使用GeoIPCountryWhois2进行csv阅读器.

  2. 使用lineterminator进行疯狂猜测可以解决您的问题

    for num,row in enumerate(csv.reader(f,lineterminator='\n'))
    
    Run Code Online (Sandbox Code Playgroud)

    另见:http://docs.python.org/lib/csv-fmt-params.html