简体   繁体   English

当标题字段由空格分隔时解析 CSV 文件

[英]Parsing CSV File when header fields separated by Space

I have a code below that I use to get the lat and long values from a textfile when the header fields are separated by comma.我在下面有一个代码,当标题字段用逗号分隔时,我用来从文本文件中获取纬度和经度值。 But recently I had an instance where the header fields were separated by SPACE instead of comma.但是最近我有一个实例,其中标题字段用空格而不是逗号分隔。 So when I ran this script below, it gave me an error.所以当我在下面运行这个脚本时,它给了我一个错误。 I am wondering if anyone knows how I can modify the script below so the header fields that are separated by SPACE can be parsed out.我想知道是否有人知道我如何修改下面的脚本,以便可以解析出由 SPACE 分隔的标题字段。

inFile = "file Path"

gps_track = open(inFile, 'r')

csvReader = csv.reader(log)
header = csvReader.next()

latIndex = header.index("lat")
longIndex = header.index("long")

coordlist = []

for row in csvReader:

    lat = row[latIndex]
    long = row[longIndex]
    coordlist.append([lat,long])

print coordlist

https://docs.python.org/2/library/csv.html https://docs.python.org/2/library/csv.html

csv.reader can take a delimiter as a parameter: So you could simply fix this by using csv.reader(log, delimiter=' ') csv.reader可以将分隔符作为参数:所以你可以简单地使用csv.reader(log, delimiter=' ')

You haven't made clear if you want both delimiters to be in use.您还没有明确表示是否要同时使用两个分隔符。 But in order to get values seperated with whitespace you should change this line:但是为了获得用空格分隔的值,您应该更改此行:

csvReader = csv.reader(log)

to

csvReader = csv.reader(log, delimiter=' ')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM