1

I'm trying to print every element in the second text file for each element in the first text file. When running the nested for loop, it's only printing every element from the second text file with the first element from the first text file.

Code:

colors = open("colorsList.txt", "r")
cars = open("carsList.txt", "r")

for color in colors:
    for car in cars:
        print(color + car)

colors.close()
cars.close()

An example is trying to print: bluemustang, bluecamaro, bluetacoma, red mustang, redcamaro, redtacoma, etc.

Edit:

The files contain every possible color and car in text files. I'm basically trying to concatenate every element in the car list with every element in the color list.

1 Answers1

0

File objects keep your position as you go through them and iterating on them is therefore memory efficient. They aren't keeping a list of the items in them. In your code, you open both files first and then iterate color_1 with each item in cars. When you move on to color_2 there is nothing left to iterate in cars. You are at the end of the file as far as Python is concerned and therefore it no longer returns anything.

In order to do what you want, you can either read everything in and store them as some iterable (list, tuple, etc), or you can open the file multiple times like below:

with open("colorsList.txt", "r") as colors:
    for color in colors:
        with open("carsList.txt", "r") as cars:
            for car in cars:
                print(f'{color} {car}')

I also changed it to use with as a context manager which will handle closing the file properly for you.

This method is going to be very memory efficient because you aren't storing the values but probably in theory would take slightly longer than storing the values and iterating over that object instead, especially if you stored them as you iterated the first time.

MyNameIsCaleb
  • 4,409
  • 1
  • 13
  • 31