List Index out of range in for loop in google colab

Viewed 283

I'm trying to combine respective lines from two files and then write it in a third file, but it's giving an index out of range error In this line: sentencelist = file.readlines()[i].strip("\n") + file1.readlines()[j].strip("\n") Here's the entire code:

file = open("task4.txt", "r")
file1 = open("task4part2.txt", "r")
file2 = open("task4part3.txt", "w") 

sentencelist = []

for i in range(len(file.readlines())):
  for j in range(len(file1.readlines())):
     if i == j:
        sentencelist =  file.readlines()[i].strip("\n") + file1.readlines()[j].strip("\n")

print(sentencelist)

Also, I'm doing this in google colab. So maybe I'm missing something there? Thanks in Advance.

1 Answers

The readlines function only works once, so try this:

file = open("task4.txt", "r")
file1 = open("task4part2.txt", "r")
file2 = open("task4part3.txt", "w") 
lines = file.readlines()
lines1 = file1.readlines()

sentencelist = []

for i in range(len(lines)):
  for j in range(len(lines1)):
     if i == j:
        sentencelist =  lines[i].strip("\n") + lines1[j].strip("\n")

print(sentencelist)
Related