我是一名初学者程序员,正在编写一个 Python 脚本,最终需要提取三列的内容并将它们写入一个新的文本文件。测试脚本时,我不断收到错误消息:IndexError: list index out of range
应用到我需要提取的第三列。
我的代码:
for ip in open("list.txt"):
with open(ip.strip()+".txt", "a") as ip_file:
for line in open("data.txt"):
new_line = line.split(" ")
if "blocked" in new_line:
if "src="+ip.strip() in new_line:
ip_file.write(", " + new_line[11])
ip_file.write(", " + new_line[12])
ip_file.write(", " + new_line[14] + "\n")
在 中的几行中data.txt
,没有第 15 列。我尝试了几种方法来避免错误消息,但我仍然收到错误:
if "src="+ip.strip() in new_line:
ip_file.write(", " + new_line[11])
ip_file.write(", " + new_line[12])
if new_line[14] is None:
pass
else:
ip_file.write(", " + new_line[14] + "\n")
和
if "src="+ip.strip() in new_line:
ip_file.write(", " + new_line[11])
ip_file.write(", " + new_line[12])
if not new_line[14]:
pass
else:
ip_file.write(", " + new_line[14] + "\n")
问题:是否有另一种方法来检查列是否存在,如果不存在则忽略?
谢谢!