Assigning `.txt` file contents to a list in python

Question:

I am making an app that stores its settings in a .txt file.
I am able to get the line count, but I don’t know, how to store the different lines as values in a list.

For example:

linecount = 0
datainfile = [] 

with open("txt.txt" , "r") as t:
    linecount += 1

config1 = datainfile[0] 

I have tried looking around on the internet, but could not find anything.

Asked By: Tetrapak

||

Answers:

First, it is always a good practice to use context manager when opening a file (using the with keyword). Second, read the file to a list and address the line number by index.

import os


with open("config.txt", "r") as cf:
    file_lines = [line.replace(os.linesep, "") for line in cf.readlines()]

Now each index in file_lines is relative to the line number in the file.

Answered By: Ilya

This is how I did it:

lines = [] 
with open("txt.txt", "r") as t:
    for i in t:
        lines.append(t)
config1 = datainfile[0]
Answered By: Tetrapak