简体   繁体   English

从python中的文本文件返回多行

[英]Returning multiple lines from a text file in python

I had a function which I wanted to read a file and return multiple values from it though I'm having trouble understanding how this would work. 我有一个函数,我想读取文件并从中返回多个值,尽管我无法理解其工作原理。 For example if my text file look like this: 例如,如果我的文本文件如下所示:

John 2543
Jack 2453
Henry 3672
Jane 2405 
Terry 9863

And my code like this: 我的代码是这样的:

def function(): 

    file = open('file.txt')    

    for lines in file:
        name, number = lines.split(' ')
        return name

def main():
    print(function())

main()

This only returns a name from one line where as I want the entire first column. 这仅从一行中返回一个名称,因为我需要整个第一列。 I understand that if I did a print function instead of return one that would work. 我知道,如果我执行打印功能而不是返回功能,那将是可行的。 However, in this scenario I would like to return the values so that I can use them in conjunction with my other functions. 但是,在这种情况下,我想返回这些值,以便可以将其与其他函数结合使用。 Thank you. 谢谢。

EDIT: 编辑:

I also had a follow up question as to how I would print the two columns side by side while dedicating a function to each column. 我还有一个后续问题,关于如何在将功能分配给每一列的同时并排打印两列。 So normally, when I print one column after another it would appear as: 因此,通常情况下,当我一列接另一列打印时,它将显示为:

John 
Jack 
Henry 
Jane 
Terry 
2543
2453
3672
2405 
9863

when I want them to appear as: 当我希望它们显示为:

John 2543
Jack 2453
Henry 3672
Jane 2405 
Terry 9863

When you return a value the function ends and control returns immediately to the function that called it. 当您返回一个值时,函数结束,并且控件立即返回到调用它的函数。 So when you return inside the loop, you never execute the loop more than once before the function exits and hands its return value to the calling function. 因此,当您在循环内返回时,在函数退出并将其返回值交给调用函数之前,您绝不会多次执行循环。

You need to build the entire list first, and then return it. 您需要先构建整个列表, 然后将其返回。

def function():
    with open('file.txt') as file:
        names = []
        for line in file:
            names.append(line.split()[0])

    return names

or 要么

def function():
    with open('file.txt') as file:
        return [line.split()[0] for line in file]

and use it like this: 并像这样使用它:

def main():
    for name in function():
        print(name)

here is a solution with a generator. 这是发电机的解决方案。 yield ing every line of your file may come in handy if your file is large. yield荷兰国际集团的文件的每一行可以派上用场,如果你的文件很大。 that prevents that the whole file has to be read into memory. 这样可以避免将整个文件读入内存。

the contents of the file are then handled in a for loop. 然后在for循环中处理文件的内容。

also note the with statement to open the file. 还请注意with语句以打开文件。 this takes care of closing it (even if the program crashes) and is the pythonic way to read from a file. 这会确保关闭它(即使程序崩溃)也是从文件读取的pythonic方法。

def function():

    with open('file.txt') as file:

       for line in file:
           name, value = line.split()
           value = int(value)
           yield name, value

# here you can do what you need to for all the data in the file
for name, value in function():
    print(name, value)

i took the liberty to cast value to an int . 我自由地为一个int贡献了value do not know if that is useful to you... 不知道这是否对您有用...

if you need to change row/column, then you have to read all to memory and you could to this: 如果您需要更改行/列,则必须将所有内容读取到内存中,并且可以这样做:

data = [(names, values) for names, values in function()]
names = [item[0] for item in data]
values = [item[1] for item in data]

you could then pretty-print that with: 然后,您可以使用:

separator = '|'
name_lst = ['{:6s}'.format(name) for name in names]
value_lst = ['{:<6d}'.format(value) for value in values]

# join the lists to str
print(separator.join(name_lst))
print(separator.join(value_lst))

# John  |Jack  |Henry |Jane  |Terry 
# 2543  |2453  |3672  |2405  |9863 

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

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