user8521874
user8521874

Reputation: 89

saving data from for loop to single list

I have a file upload page where users upload their files and they are generally bunch of files.In my python code I am trying to pull a tag out from that file and then save it into a list, so everything works fine but here I am getting three different output lists for 3 files uploaded. How do I combine the 3 output lists into just one.Here is my code

    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)

the output I get is:

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

I would like to combine all into just one list

Upvotes: 1

Views: 57

Answers (1)

Chetan_Vasudevan
Chetan_Vasudevan

Reputation: 2414

As far as I analyzed I think you want to write all the soc_list values to a single file and then you can read the file back. Doing this would be the best way for you because you will not know the user file uploads as you mentioned in your question. To do so try to understand and implement this code below to save to your file

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

This way you can always write things to your file and then to read back your data and converting it into list follow this example as below

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

Upvotes: 1

Related Questions