Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

save url as a file name in python

Tags:

python

I have a url such as

http://example.com/here/there/index.html

now I want to save a file and its content in a directory. I want the name of the file to be :

http://example.com/here/there/index.html

but I get error, I'm guessing that error is as the result of / in the url name.

This is what I'm doing at the moment.

        with open('~/' + response.url, 'w') as f:
            f.write(response.body)

any ideas how I should do it instead?

like image 894
nafas Avatar asked Dec 02 '14 15:12

nafas


People also ask

How do you give a URL in Python?

In the urllib module, various classes and functions are defined, which help us to perform various url actions using a Python program. We will use the urlopen() method by importing urllib. request library in the program, and then we give url inside this function so that it will open in the browser of our device.


1 Answers

You could use the reversible base64 encoding.

>>> import base64
>>> base64.b64encode('http://example.com/here/there/index.html')
'aHR0cDovL2V4YW1wbGUuY29tL2hlcmUvdGhlcmUvaW5kZXguaHRtbA=='
>>> base64.b64decode('aHR0cDovL2V4YW1wbGUuY29tL2hlcmUvdGhlcmUvaW5kZXguaHRtbA==')
'http://example.com/here/there/index.html'

or perhaps binascii

>>> binascii.hexlify(b'http://example.com/here/there/index.html')
'687474703a2f2f6578616d706c652e636f6d2f686572652f74686572652f696e6465782e68746d6c'
>>> binascii.unhexlify('687474703a2f2f6578616d706c652e636f6d2f686572652f74686572652f696e6465782e68746d6c')
'http://example.com/here/there/index.html'
like image 123
Reut Sharabani Avatar answered Nov 02 '22 06:11

Reut Sharabani