我遇到了一些问题,想将一个文本文件转换成由逗号分隔的列表组成的列表。基本上,我需要:
DATE OF OCCURRENCE,WARD,LONGITUDE,LATITUDE
06/04/2011,3,-87.61619704286184,41.82254380664193
06/04/2011,20,-87.62391924557963,41.79367531770095
看起来像:
[["DATE OF OCCURRENCE", "WARD", "LONGITUDE" , "LATITUDE"],
["06/04/2011", "3", "-87.61619704286184", "41.82254380664193"],
["06/04/2011", "20", "-87.62391924557963", "41.79367531770095"]]
这是我目前的代码:
row = []
crimefile = open(fileName, 'r')
for line in crimefile.readlines():
row.append([line])
for i in line.split(","):
row[-1].append(i)
然而,这给我带来了以下结果:
[['DATE OF OCCURRENCE,WARD,LONGITUDE,LATITUDE\n', 'DATE OF OCCURRENCE', 'WARD', 'LONGITUDE', 'LATITUDE\n'],
['06/04/2011,3,-87.61619704286184,41.82254380664193\n', '06/04/2011', '3', '-87.61619704286184', '41.82254380664193\n'],
['06/04/2011,20,-87.62391924557963,41.79367531770095', '06/04/2011', '20', '-87.62391924557963', '41.79367531770095']]
我只想能够删除第一部分并用第二部分替换它。我该怎么做?
.readlines()
,会更好,因为它是(1)没有必要的,(2)什么也没用就占用了内存。实际上,你可以简单地使用[… for line in crimeFile]
,Python将简单地迭代文件的每一行并几乎不使用任何内存,而不是使用readlines()
将整个文件读入内存并将所有行放入列表中(这将占用内存)。 - Eric O. Lebigot