Having trouble creating a new file and then manipulating its contents
<p>My goal is to create a python program that will receive user input to open a specific file, copy the contents of that file into a new file (named by the user), and then remove all spaces and digits from the new file.</p>

<p>I am successfully copying the contents of my 'sequence' file into a newly-created 'newsequence' file. Everything falls apart in my second 'for' loop when I then try to manipulate the 'newsequence' file.</p>

<p>I was running into an error where it couldn't read 'newsequence' (maybe because it thought I wanted it to read a variable, rather than the contents of a file?). I thought converting the file to a string might help (although I admit I thought it should have worked without doing so), so in line 7 I converted 'newsequence' to a string.</p>

<p>This at least got the program to run to completion, without raising the "io.UnsupportedOperation: not readable" error, but it's still not right. My output file is identical to the original 'sequence' file, except it contains an extra line at the end that simply reads, "8". Where is this "8" coming from, and what changes do I need to make to my code to get it to do what I want it to do?</p>

<p>I am very new to programming, so I am likely making a series of silly mistakes. Thank you for any help you can give me.</p>

<pre><code>sequence = open(input("Choose sequence file: "))
name = input('Enter name of new text file, without .txt: ') + '.txt'

with open(name, 'a') as newsequence:
        for line in sequence:
                newsequence.write(line)
        for line in str(newsequence):
                result = ''.join(i for i in line if i.isdigit())
                result = result.replace(" ","")
                newsequence.write(result)
sequence.close()
newsequence.close()
</code></pre>

<p>Why don't you do this in one <code>for</code> loop ? </p>

<p>Not tested:</p>

<pre><code>file_in = open(input("Choose sequence file: "))

name = input('Enter name of new text file, without .txt: ') + '.txt'

with open(name, 'a') as file_out:
    for line in file_in:
        line = ''.join(i for i in line if i.isdigit())
        line = line.replace(" ","")
        file_out.write(line)

file_in.close()
</code></pre>

<p>You can't read (line by line) and write (line by line) in the same file - you will overwrite old text before you read it. </p>

python