Python读取txt文件并创建数组列表

时间:2017-08-25 10:03:16

标签: python arrays list

我有一个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)

但我有这个错误: 对于io.StringIO中的行(内容).readlines()[1:]:#跳过第一行 TypeError:initial_value必须是unicode或None,而不是str

2 个答案:

答案 0 :(得分:3)

使用名称更新并转换为浮动

这样的事情怎么样?

BULK_LOGGED

返回:

import io

string = u"""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"""

output = []

#with open("pathtofile.txt") as file:
#    for row in file.readlines()[1:]
    #code here

for row in io.StringIO(string).readlines()[1:]: # skips first row
    if row.startswith("Name"):
        i = row.split(":")[1].strip()
    else:
        output.append([i]+[float(item.strip()) for item in row.split(",")])

output

答案 1 :(得分:1)

python3解决方案:

`result_list = []
 with open(your_file, 'r') as file_:
    file_.readline() # skip the header, apparently you don't want it.

    for line in file_:
        if line.startswith('Name'):
            current_tag = line.strip().split()[-1] # assume that the tag as no space
          # else use split(':')[-1].strip()
            continue 
        result_list.append([current_tag] + line.strip().split(','))

`