Python - insert lines on txt following a sequence without overwriting
Question: I want to insert the name of a file before each file name obtained through
glob.glob, so I can concatenate them through FFMPEG by sorting them into
INTRO+VIDEO+OUTRO, the files have to follow this order:

INSERTED FILE NAME  
FILE  
INSERTED FILE NAME  
INSERTED FILE NAME  
FILE  
INSERTED FILE NAME  
INSERTED FILE NAME  
FILE  
INSERTED FILE NAME  

This is this code I'm using:

    
    
    import glob
    open("Lista.txt", 'w').close()
    file = open("Lista.txt", "a")
    list =glob.glob("*.mp4")
    for item in list:
      file.write("%s\n" % item)
    file.close()
    
    f = open("Lista.txt", "r")
    contents = f.readlines()
    f.close()
    
    for x,item in enumerate(list):
        contents.insert(x, "CTA\n")
    f = open("Lista.txt", "w")
    contents = "".join(contents)
    f.write(contents)
    print f
    f.close()
    

But I obtain the values in the wrong order:  

INSERTED FILE NAME  
INSERTED FILE NAME  
INSERTED FILE NAME  
FILE  
FILE  
FILE  

How could I solve this? EDIT: As pointed out, maybe the issue is being caused
by modifying a list that I'm currently using.


Answer: You are trying to modify `contents` list. I think if new list is used to get
final output, then it will be simple and more readable as below. And as **Zen
of Python** states

**Simple is always better than complex.**

  1. Consider you got `file_list` as below after doing `glob.glob`.

> file_list = ["a.mp4","b.mp4","c.mp4"]

  2. Now you want to add "`INSERTFILE`" before and after every element of `file_list` so that final_list will look like 

> final_list = ['INSERTFILE', 'a.mp4', 'INSERTFILE', 'INSERTFILE', 'b.mp4',
> 'INSERTFILE', 'INSERTFILE', 'c.mp4', 'INSERTFILE']

  3. This final_list you will write to file.

**_Problem summary is how to achieve step 2._**

Below code will get step 2.

**Code (with comments inline:**

    
    
    #File List from glob.glob
    file_list = ["a.mp4","b.mp4","c.mp4"]
    #File to be added
    i = "INSERTFILE"
    final_list = []
    for x in file_list:
        #Create temp_list
        temp_list = [i,x,i]
        #Extend (not append) to final_list
        final_list.extend(temp_list)
        #Clean temp_list for next iteration
        temp_list = []
    print (final_list)
    

**Output:**

    
    
    C:\Users\dinesh_pundkar\Desktop>python c.py
    ['INSERTFILE', 'a.mp4', 'INSERTFILE', 'INSERTFILE', 'b.mp4', 'INSERTFILE', 'INSERTFILE', 'c.mp4', 'INSERTFILE']
    

