'Change file extension of download with Python

If I'm downloading a file with a certain extension from a certain link, but want to download the file with another extension (e.g. .doc instead of .bin), how would I go about doing this in python code?



Solution 1:[1]

It can be done in the following way:

  1. Download file in the default / original format
  2. Use pypandoc in a Python script to create a new file with the desired format from the original file.
  3. delete original file.

These 3 steps can all be automated from a Python script.

https://pypi.org/project/pypandoc/

Example, convert a markdown file to a rst-file (remember to correct the URL):

import os
import requests

import pypandoc

# Download file
# TODO: Update URL
url = 'some_url/somefile.md'
r = requests.get(url)
orig_file = '/Users/user11508332/Downloads/somefile.md'
with open(orig_file, 'wb') as f:
    f.write(r.content)

# pypandoc file extention conversion
output = pypandoc.convert_file(orig_file, 'rst')

# TODO: Place a check here to see if the new file got created

# Clean-up: Delete original file
# TODO: Place a check here to see if the old file still exists, in that case, proceed with deletion:
# os.remove(orig_file)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1