0

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

Marouen
  • 907
  • 3
  • 13
  • 36
Hy.DRO
  • 25
  • 5
  • 2
    Consider using a list of strings instead of a different variable for each string. – John Anderson Apr 14 '19 at 13:57
  • Yeah so should i use readline() or readlines() ? And how should i do ? – Hy.DRO Apr 14 '19 at 14:01
  • If you're making a line by line list from the text file you can read it and split it by new line so you don't have to go back and use strip each item again. `with open('file.txt') as f: print(f.read().split('\n'))` – nicholishen Apr 14 '19 at 14:09

2 Answers2

0

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
0

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 :)