【发布时间】:2017-08-25 10:03:16
【问题描述】:
我有一个 txt 文件,我用我的 python 代码逐行读取:
a = open("data.txt","r")
inputF = a.readlines()
for line in inputF:
print(line)
我的 txt 文件是这样的:
Data: 7_8_2014
Name: Road
488597.653655, 4134910.76248
488813.848952, 4134609.01192
488904.303214, 4134480.54842
488938.462756, 4134422.3471
Name: Street
496198.193041, 4134565.19994
496312.413827, 4134568.14182
496433.652036, 4134568.08923
496559.933558, 4134547.91561
496782.196397, 4134527.70636
496923.636101, 4134512.56252
我想读取这个文件 txt 并创建一个列表数组,如下所示:
coordsList = [[Road, 488597.653655, 4134910.76248],
[Road, 488813.848952, 4134609.01192],
[Road, 488904.303214, 4134480.54842],
[Road, 488938.462756, 4134422.3471],
[Street, 496198.193041, 4134565.19994],
[Street, 496312.413827, 4134568.14182],
[Street, 496433.652036, 4134568.08923],
[Street, 496559.933558, 4134547.91561],
[Street, 496782.196397, 4134527.70636],
[Street, 496923.636101, 4134512.56252]]
将每个标签“名称”写入txt文件。
在您 (Anton vBR) 的帮助下,我以这种方式更新了我的代码:
import arcpy
import os, sys
import io
with open('C:/Users/fdivito/Desktop/FinalProjectData/7_8_2014.txt', 'r') as content_file:
content = content_file.read()
i=0
output = []
for row in io.StringIO(content).readlines()[1:]: # skips first row
if row.startswith("Name"):
#i = row.split(":")[1].strip()
i+=1
else:
output.append([i]+[float(item.strip()) for item in row.split(",")])
print(output)
但我有这个错误: for row in io.StringIO(content).readlines()[1:]: # 跳过第一行 TypeError: initial_value 必须是 unicode 或 None,而不是 str
【问题讨论】:
-
您需要检查行是否包含文本名称,然后采取相应措施。您可以在行语言结构中使用 if "Name"。
-
您的列表中有哪些数字?
-
您确实意识到您在示例文件中拥有的数据与您说您想要在列表中的数据无关。这可能会引起一些混乱。
-
我已经修好了