简体   繁体   English

如何在Python中分别为txt中的每一行分配变量?

[英]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.谢谢。

You don't need all these slices and indices.您不需要所有这些切片和索引。 Just use readline :只需使用readline

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

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

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM