I'm making a saving system for a program and I didn't find how to attribute each line of my .txt file to a variable.
For example :
a = The first line of my txt file
b = The second line etc...
Is there a better way to make this ?
Thanks
I'm making a saving system for a program and I didn't find how to attribute each line of my .txt file to a variable.
For example :
a = The first line of my txt file
b = The second line etc...
Is there a better way to make this ?
Thanks
This is a function which will turn your file into a list:
def txt_to_list(file_location):
    all_data = []
    opened_file = open(str(file_location), "r")
    data = opened_file.readline().strip()
    while data != "":
        all_data.append(data)
        data = opened_file.readline().strip()
    opened_file.close()
    return all_data
Instead of having so many variables, a better solution would be to use a dictionary instead. So basically something like:
my_dictionary = {}
with open('sentences.txt', 'r') as file:
    lines = file.readlines()
    for line in lines:
        my_dictionary[lines.index(line)] = line.strip()
print(my_dictionary)
So to access the line, you can just access the key of that dictionary, making your code efficient and clean :)
