python - 获取:尝试读取文本文件时出现索引超出列表错误
问题描述
我正在尝试使用 Python 将数据集中的所有浮点元素提取到三列中。但我得到一个索引超出范围错误。
#Reading the file line by line, separating each line by columns
file1=open("./Marine/bath.txt","r")
x=[]
y=[]
z=[]
i=1
for line in file1: ### Reading sequencially the lines of the file1 object
if i>4:
columns=line.split()
x.append(float(columns[3]))
y.append(float(columns[1]))
z.append(float(columns[5]))
i=i+1
file1.close()
x=np.array(x)
y=np.array(y)
z=np.array(z)
print("Number of lines read :",i-1)
print("Number of samples read from the file:",len(x))
数据如下所示:
zzzzzzz 50.0 ttttttt 329365.108 bbbbbbbb 4358562.104
zzzzzzz 220.00000000000003 ttttttt 402708.003 bbbbbbbb 4344547.635
zzzzzzz 110.00000000000001 ttttttt 347930.603 bbbbbbbb 4233132.610
以 zzzzzzz 作为每一行的开头
解决方案
您的脚本适用于您提供的数据。问题很可能在输入文件中找到。如果文件中只有一行不符合数据格式(即少于 6 列,或者可能是空行),则其中一个columns[n]
语句会触发索引超出范围错误。
推荐阅读
- python - 无法将字符串正确格式化为日期时间
- html - 自动包装 CSS3-grid(自动调整)和各种宽度
- python - 从 csv 文件替换 yaml 中的每个出现
- sql - delta - 表合并 sql - 我如何更新目标中的所有列,除了一列仅用于更新子句
- python - 如何在 python 中的 selenium 中获取此特定元素
- python - [已解决]我无法通过 pip install filename.whl 安装库
- cookies - 所有网站均可访问 Cookie
- docker - docker-compose --build 需要很长时间,占用大量空间
- flask - 如何运行烧瓶以利用系统范围的可信证书进行 https 访问?
- swift - Xcode 游乐场上的 SwiftUI 和 foreach 问题