I'm a beginner programmer writing a Python script which ultimately needs to pull the contents of three columns and write them to a new text file. When testing the script, i keep getting the error: IndexError: list index out of range
applying to the third column I need to pull.
My code:
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")
In a few of the lines in data.txt
, there is no 15th column. I have tried a couple ways to avoid the error message, but I still get the error:
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")
and
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")
Question: Is there another way to check if the column exists and ignore if does not?
Thanks!