-2

I have a text file that with multiple lines and I'm trying to assign turn every line into a string and assign them into a variable separately. The code looks something like this at the moment:

with open('config.txt', 'r') as f:
    file_name = ''.join(f.readlines()[0:1])
    Runstart = ''.join(f.readlines()[1:2])
    Runend = ''.join(f.readlines()[2:3])

But it doesn't read anything after the first line. What am I doing wrong here and how do I fix it? The goal is to give a name for every line. Alternative methods are welcomed.

Thanks.

jxaiye
  • 13
  • 4
  • 1
    Did you mean: `f.readline()`? – quamrana Sep 02 '22 at 14:33
  • 2
    Well, it was just a guess. You should specify what is in your file and what you want to get transferred to your variables. Please update your question with this information. – quamrana Sep 02 '22 at 14:39

3 Answers3

2

You don't need all these slices and indices. Just use readline:

with open('config.txt', 'r') as f:
    file_name = f.readline()
    Runstart = f.readline()
    Runend = f.readline()
0

You can treat the file as an iterator.

from itertools import islice

with open('config.txt', 'r') as f:
    file_name, Runstart, Runend = (x.rstrip() for x in islice(f, 3))
chepner
  • 497,756
  • 71
  • 530
  • 681
-2

not sure if this helps but this is what I understand from your question:

with open('config.txt', 'r') as f:
    for line in f:
        thisList = line.split(' ')
        string = ''
        file_name = thisList[0]
        Runstart = thisList[1]
        Runend = thisList[2]
        print(file_name, Runstart, Runend)