Saving a webpage to text file I'm trying to save a webpage as text file, using the following function:

def html_to_txt(): 
    import urllib.request 
    url = str(input('Enter URL: ')) 
    page = urllib.request.urlopen(url) 
    with open(str(input('Enter filename: ')), "w") as f: 
        for x in page: 
            f.write(str(x).replace('\\n','\n')) 
    s= 'Done' 
    return s


It gives a correct output, that means I can save a given webpage. But, the final text file contains a b' before the very first line, and a 'b' before each following line.

Here's a sample output of my function (taken from: http://www.uniprot.org/uniprot/P57052.txt)

$ cat P57052.txt
b'ID   RBM11_HUMAN             Reviewed;         281 AA.
'b'AC   P57052; Q6YNC2; Q8NBA1; Q8NFF6;
'b'DT   01-DEC-2000, integrated into UniProtKB/Swiss-Prot.
'b'DT   01-DEC-2000, sequence version 1.
'b'DT   09-JUL-2014, entry version 111.
'b'DE   RecName: Full=Splicing regulator RBM11;
'b'DE   AltName: Full=RNA-binding motif protein 11;
'b'GN   Name=RBM11;


I wonder if it has something to do with binary file "default", I mean, if the webpage is  automatically saved with binary features by my python script.

Thanks in advance for your review.
As a review, the code needs some work with regard separation of concerns. A single function shouldn't get user input, get a URL and write to a file. If you try to write unit tests for it, you'll quickly see it's better to split the functionality.

With regard to the problem, try something as follows:

import urllib2

url = 'http://www.uniprot.org/uniprot/P57052.txt'
response = urllib2.urlopen(url)
with open('output.txt', 'w') as f:
    f.write(response.read())


I hope this helps.