我想将数据从文本文件传输到数组

2024-04-19 10:59:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我是新来的,对python编程也很陌生 作为练习,我必须从包含许多行的txt文件中读取数据(lat&lon),并使用QGIS将它们转换为shapefile

在阅读之后,我找到了一种将数据提取到数组中的方法,如步骤1,但是我有soem问题。。你知道吗

我使用以下代码

X=[]
Y=[]
f = open('D:/test_data/test.txt','r')
for line in f:
   triplets=f.readline().split()  #error
X=X.append(triplets[0])
Y=Y.append(triplets[1])
f.close()
for i in X:
     print X[i]

有错误:

ValueError: Mixing iteration and read methods would lose data

可能这是一个警告,为失去其余的行,但我真的不想他们现在。你知道吗


Tags: 文件intesttxtfordata编程读取数据
2条回答

line已经是行了。把三胞胎拿过来

triplets = line.split()

for line in f:已经在文件中的行中迭代,边读边读。因此,应该是:

for line in f:
    triplets = line.split()

或者,你可以做如下,尽管我推荐上面的方法。你知道吗

with open('D:/test_data/test.txt','r') as f:
    content = f.readlines()
    for line in content:
        triplets = line.split()
        # append()

有关详细信息,请参见python中的Reading and Writing Files。你知道吗

另外,append()做它听起来像什么,所以你不需要赋值。你知道吗

X.append(triplets[0])  # not X=X.append(triplets[0)

相关问题 更多 >