Python - insert lines on txt following a sequence without overwriting
<p>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:</p>

<p>INSERTED FILE NAME<br>
FILE<br>
INSERTED FILE NAME<br>
INSERTED FILE NAME<br>
FILE<br>
INSERTED FILE NAME<br>
INSERTED FILE NAME<br>
FILE<br>
INSERTED FILE NAME<br></p>

<p>This is this code I'm using:</p>

<pre><code>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()
</code></pre>

<p>But I obtain the values in the wrong order:<br></p>

<p>INSERTED FILE NAME<br>
INSERTED FILE NAME<br>
INSERTED FILE NAME<br>
FILE<br>
FILE<br>
FILE
<br></p>

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

<p>You are trying to modify <code>contents</code> list. I think if new list is used to get final output, then it will be simple and more readable as below. And as <strong>Zen of Python</strong> states</p>

<p><strong>Simple is always better than complex.</strong> </p>

<ol>
<li>Consider you got <code>file_list</code> as below after doing <code>glob.glob</code>.</li>
</ol>

<blockquote>
  <p>file_list = ["a.mp4","b.mp4","c.mp4"]</p>
</blockquote>

<ol start="2">
<li>Now you want to add "<code>INSERTFILE</code>" before and after every element of <code>file_list</code> so that final_list will look like </li>
</ol>

<blockquote>
  <p>final_list = ['INSERTFILE', 'a.mp4', 'INSERTFILE', 'INSERTFILE',
  'b.mp4', 'INSERTFILE', 'INSERTFILE', 'c.mp4', 'INSERTFILE']</p>
</blockquote>

<ol start="3">
<li>This final_list you will write to file.</li>
</ol>

<p><strong><em>Problem summary is how to achieve step 2.</em></strong></p>

<p>Below code will get step 2.</p>

<p><strong>Code (with comments inline:</strong></p>

<pre><code>#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)
</code></pre>

<p><strong>Output:</strong></p>

<pre><code>C:\Users\dinesh_pundkar\Desktop&gt;python c.py
['INSERTFILE', 'a.mp4', 'INSERTFILE', 'INSERTFILE', 'b.mp4', 'INSERTFILE', 'INSERTFILE', 'c.mp4', 'INSERTFILE']
</code></pre>

python video ffmpeg