【发布时间】:2018-06-19 15:05:20
【问题描述】:
我想将特定列(以下输入文件 xyz.txt 中的 z 列)中的所有数字乘以因子 3 并将其输出到文本文件中。当我运行 ./script.py xyz.txt > output.txt 时,我收到此错误:
Traceback(最近一次调用最后一次):文件“./script.py”,第 23 行,在 sys.exit(main(sys.argv)) 文件“./script.py”,第 18 行,在 main result.append(z.split(' ')[2]*3) IndexError: list index out of range
你知道我该如何解决这个错误吗?
script.py:
#!/usr/bin/env python3
def main(argv):
inputfile = open(argv[1])
line = inputfile.readline()
while line:
print(line, end="")
if line.startswith('[ xyz ]'):
break
line = inputfile.readline()
result=[]
for z in line:
result.append(z.split(' ')[2]*3)
print(z.rstrip(), '; modified')
if __name__ == "__main__":
import sys
sys.exit(main(sys.argv))
输入文件xyz.txt:
[ xyz ]
; x y z
1.5 3.5 6.3
2.4 4.2 2.4
3.2 8.9 8.9
4.3 2.1 9.2
5.4 6.3 3.5
请求的输出文件 output.txt:
[ xyz ]
; x y z
1.5 3.5 18.9 ; modified
2.4 4.2 7.2 ; modified
3.2 8.9 26.7 ; modified
4.3 2.1 27.6 ; modified
5.4 6.3 10.5 ; modified
【问题讨论】:
-
您似乎正在像换行符一样拆分绞线。此外,您应该使用
csv模块来读取更适合此类任务的文件。或者作为更好的方法,您可以使用numpy或pandas模块。 -
你可以做
if (len(z.split(' ')>2): result.append(z.split(' ')[2]*3) -
@erhan:您必须将文件转储为 txt。您还需要管理列表中 z 值的索引。
标签: python python-3.x numpy