Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to assign variable for every line in txt seperately in Python?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading