1

I use django 1.11 and python 3.6 I have several text file links Example:

http://mylinks/telechargement.php?file=file1.txt

http://mylinks/telechargement.php?file=file2.txt

Now It's possible to download it with python code ?

How can I download each of these files via the link and save it to a specific directory with python code without modifyin its structure ? Thank for advance.

Mbambadev
  • 729
  • 1
  • 7
  • 26
  • 1
    this [answer](https://stackoverflow.com/a/16174886/5644965) will point you in the right direction – Lemayzeur May 01 '18 at 16:08
  • Yes ! But after many times to patients and research it's one of true. Now if you have better for me i accept. Not to mention that I would like to display a progress bar on the view telling me the progress of the download. Without using an external library (like jquery, or other). Mainly python code, knowing that I'm using django 1.11 and python 3.6 – Mbambadev May 02 '18 at 06:15

1 Answers1

4

If you make use of the popular requests library, here's a simplistic solution for downloading a TXT file to a specific path:

import requests

example_txt = 'http://www.textfiles.com/100/914bbs.txt'

r = requests.get(example_txt)
with open('/path/to/file.txt', 'wb') as f:
    f.write(r.content)
toxefa
  • 283
  • 2
  • 10
  • ohhhhh Yessssss my friend ! I remember now that r.content is binary ! – Mbambadev May 01 '18 at 15:00
  • This is helpful! If I have to hit a URL several times to get an updated txt file, and I use this code to save it, will it automatically replace the previous txt file I saved? – impostorsyndrome Oct 28 '20 at 20:15
  • @impostorsyndrome yes that’s correct. Opening a file with ‘w’ means write mode - to just append to the end of the existing file you would use ‘a’ (in this case ‘ab’ because we’re writing binary data). You’ll find all the various ‘mode’ options in the Python docs for `open()`: https://docs.python.org/3/library/functions.html#open – toxefa Oct 29 '20 at 21:14