简体   繁体   English

只退还第一件物品

[英]Return only returning 1st item

In my function below I'm trying to return the full text from multiple .txt files and append the results to a list, however, my function only returns the text from the first file in my directory. 在下面的函数中,我尝试从多个.txt文件返回全文并将结果附加到列表中,但是,我的函数仅从目录中的第一个文件返回文本。 That said if I replace return with print it logs all the results to the console on its own line but I can't seem to append the results to a list. 就是说,如果我将return替换为print,它将所有结果记录在控制台的一行上,但是我似乎无法将结果附加到列表中。 What am I doing wrong with the return function. 我在用return函数做错了什么。 Thanks. 谢谢。

import glob
import copy

file_paths = []
file_paths.extend(glob.glob("C:\Users\7812397\PycharmProjects\Sequence      diagrams\*"))
matching_txt = [s for s in file_paths if ".txt" in s]
full_text = []
def fulltext():
    for file in matching_txt:
        f = open(file, "r")
        ftext = f.read()
        all_seqs = ftext.split("title ")
        return all_seqs
print fulltext()

You're putting return inside your loop. 您正在将return放入循环中。 I think you want to do. 我想你想做。 Although, you could yield the values here. 虽然,您可以在此处产生值。

for file in matching_txt:
    f = open(file, "r")
    ....
    full_text.append(all_seqs)
return full_text 

You can convert your function to a generator which is more efficient in terms of memory use: 您可以将函数转换为在内存使用方面更高效的生成器:

def fulltext():
    for file_name in matching_txt:
        with open(file_name) as f:
            ftext = f.read()
            all_seqs = ftext.split("title ")
            yield all_seqs

Then convert the generator to a list if they are not huge, other wise you can simply loop over the result if you want to use the generator's items: 然后将生成器转换为列表(如果它们不大),否则,如果要使用生成器的项目,则可以简单地遍历结果:

full_text = list(fulltext())

Some issues in your function: 您的函数中的一些问题:

First off, don't use python built-in names as variable names (in this case file). 首先,不要使用python内置名称作为变量名称(在本例中为文件)。 Secondly for dealing with files (and other internal connections) you better to use with statement which will close the file at the end of the block automatically. 其次,要处理文件(和其他内部连接),最好使用with语句,该语句将自动在块末尾关闭文件。

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

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