我在尝试将文本文件转换为以逗号分割的列表列表时遇到问题。基本上,我想:
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)
然而,这让我得到了结果:
[[发生日期,遗嘱,LONGITUDE,LATITUDE \ n','发生日期','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']]
我只想删除第一部分并将其替换为第二部分。我怎么能这样做?
答案 0 :(得分:16)
也许:
crimefile = open(fileName, 'r')
yourResult = [line.split(',') for line in crimefile.readlines()]
答案 1 :(得分:12)
这看起来像一个CSV文件,因此您可以使用python csv module来读取它。例如:
import csv
crimefile = open(fileName, 'r')
reader = csv.reader(crimefile)
allRows = [row for row in reader]
使用csv模块可以指定如何处理引号和换行符之类的内容。请参阅我上面链接的文档。
答案 2 :(得分:1)
继续你的开始:
row = [[]]
crimefile = open(fileName, 'r')
for line in crimefile.readlines():
tmp = []
for element in line[0:-1].split(','):
tmp.append(element)
row.append(tmp)
答案 3 :(得分:-1)
也许
对于a_file中的a_line:
lista.append(a_line)
sub to poopypie