Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将数据从for循环保存到单个列表_Python - Fatal编程技术网

Python 将数据从for循环保存到单个列表

Python 将数据从for循环保存到单个列表,python,Python,我有一个文件上传页面,用户上传他们的文件,他们通常是一堆文件。在我的python代码中,我试图从该文件中拉出一个标记,然后将其保存到一个列表中,因此一切正常,但在这里,我得到了3个上传文件的三个不同输出列表。如何将3个输出列表合并为一个。以下是我的代码 a=self.filename print(a) #this prints out the uploaded file names(ex: a.xml,b.xml,c.xml) soc_list=[] for so

我有一个文件上传页面,用户上传他们的文件,他们通常是一堆文件。在我的python代码中,我试图从该文件中拉出一个标记,然后将其保存到一个列表中,因此一切正常,但在这里,我得到了3个上传文件的三个不同输出列表。如何将3个输出列表合并为一个。以下是我的代码

    a=self.filename
    print(a) #this prints out the uploaded file names(ex: a.xml,b.xml,c.xml)
    soc_list=[]
    for soc_id in self.tree.iter(tag='SOC_ID'):
        req_soc_id = soc_id.text
        soc_list.append(req_soc_id)
    print(soc_list)
我得到的结果是:

    a.xml
    ['1','2','3']
    b.xml
    [4,5,6]
    c.xml
    [7,8,9]

我想将所有的都合并到一个列表中,因为我分析了我认为您想将所有soc\u列表值写入一个文件,然后您可以将文件读回。这样做对您来说是最好的方法,因为您不知道您在问题中提到的用户文件上载情况。为此,请尝试理解并实现下面的代码以保存到您的文件中

    save_path = "your_path_goes_here"
    name_of_file = "your_file_name"
    completeName = os.path.join(save_path, name_of_file + ".txt")
    file1 = open(completeName, 'a')
    for soc_id in self.tree.iter(tag='SOC_ID'):
        req_soc_id = soc_id.text
        soc_list.append(req_soc_id)
        file1.write(req_soc_id)
        file1.write("\n")
    file1.close()
通过这种方式,您可以始终将内容写入文件,然后读回数据并将其转换为列表,如下例所示

    examplefile = open(fileName, 'r')
    yourResult = [line.split('in_your_case_newline_split') for line in examplefile.readlines()]

您不能执行
combinedlist=[listA+listB+listC]
?,这应该会将所有列表都放在一个列表中。每次我都会得到一个不同的文件,因此不可能执行a+b+c。有时,他们可能会上传12个文件,你必须更详细地描述一下你的上下文。例如,您提供的代码是循环的一部分,循环会遍历上载的每个文件,还是您启动代码三次以生成所描述的输出?@user8521874:您是如何获得输出的。您是执行某个函数3次(例如上面的示例)还是执行一次。你总是可以连接列表。你能提供函数和上下文/进程的更多细节吗。函数被执行文件被上传的次数,所以如果我上传3个文件,它会执行3次