-2

So basically I want to create a variable that changes after every iteration of a for loop to be the same as the search term that is used in the for loop in question, is that possible? I explained better in the code I think.

with open ('lista1.txt','r') as file_1:
    reader_0 = file_1.readlines()  # Reads a list of searchterms,
                                   # the first search term of this list is "gt-710".
    for search in reader_0:
        file_0 = search.replace("\n","") +".txt"
        file_1 = str(file_0.strip())



        try: #if the file named the same as the searchterm exists, read its contents

            file = open(file_1,"r")

            search = file.readlines()  # How do I create a variable that
                                       # changes names? for example I want the
                                       # content of file readlines be saved in
                                       # a variable called the same as the
                                       # searchterm in this ase I want it to
                                       # be gt-710 = file.readlines()...in the
                                       # next iteration I want it to be
                                       # next_search_term_in_the_list =
                                       # file.readlines()..an so on...
            print(str(search) + "I actually tried")

        except: #if not, create it
            file = open(file_1,"w")
            file.write("hello")
            print("I didnt")
            file.close()
Chris Catignani
  • 5,040
  • 16
  • 42
  • 49

1 Answers1

0

This is impossible in Python, but you can do something similar. Enter stage left, the DICTIONARY! A dictionary is like a list, but you set your own keys. Make it like this:

my_dict = {}

You can add to the dictionary like so:

my_dict["key"] = "value"

A way you could implement this into your code could be as follows:

the_dict = {}
with open ('lista1.txt','r') as file_1:
[...]
            file = open(file_1,"r")
            file_contents = file.readlines()
            the_dict[search] = file_contents
            print(str(file_contents) + "I actually tried")
[...]
Seth
  • 2,214
  • 1
  • 7
  • 21