count lines and create new file
<p>So basically I have to call the text file, and create the new file while adding some strings.</p>

<p>For example if my input text is:</p>

<p>Hello</p>

<p>World</p>

<p>Nice to Meet You</p>

<p>my output text has to be:</p>

<p>1: Hello</p>

<p>2: World</p>

<p>3: Nice to Meet You</p>

<p>Below is the code that I have been trying to figure out. When I try it, there is no error, but it does not create the new file too. </p>

<pre><code>with open('filetext') as f:
    content=f.readlines()   
    for count in f:
        count+=1
        with open('newfiletext', 'a+') as f:     
        f.write(counts)
        f.write(': ')
        f.write(content)
        f.write('\n')
</code></pre>

<p>I appreciate if I can get a help. Thank you in advance.</p>

<p>First you open the file:</p>

<pre><code>with open('filetext') as f:
</code></pre>

<p>Then you read the whole thing into a list:</p>

<pre><code>content=f.readlines()   
</code></pre>

<p>Then you attempt to iterate over the now-empty file object:</p>

<pre><code>for count in f:
</code></pre>

<p>Since it's empty, nothing in the following block will execute, even once. Make sure you keep track of variable names and use a unique one for each unique object you want to manipulate - notably, <code>f</code> and <code>count</code> are reused when they shouldn't be:</p>

<pre><code>with open('filetext') as f, open('newfiletext', 'a+') as output:
    count = 0
    for line in f:
        count += 1
        output.write(count)
        output.write(': ')
        output.write(line)
</code></pre>

python