【问题标题】:Change file extension of download with Python用python更改下载的文件扩展名
【发布时间】:2020-09-17 00:20:29
【问题描述】:

如果我从某个链接下载具有特定扩展名的文件,但想下载具有其他扩展名的文件(例如 .doc 而不是 .bin),我将如何在 python 代码中执行此操作?

【问题讨论】:

    标签: python download file-extension downloadfile


    【解决方案1】:

    可以通过以下方式完成:

    1. 以默认/原始格式下载文件
    2. 在 Python 脚本中使用 pypandoc 从原始文件创建具有所需格式的新文件。
    3. 删除原始文件。

    这 3 个步骤都可以通过 Python 脚本自动完成。

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

    例如,将 markdown 文件转换为 rst-file(记得更正 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)
    

    【讨论】:

    • 如果我只有到 r = requests.get(url) 的行,那么文件应该保存在哪里?我好像没找到。
    • 在该行中,在线文件的内容被读入本地计算机内存并存储到 r 变量中
    • 然后将 r 的内容保存到本地文件系统中的一个文件中,我将其命名为 orig_file 并组成了一个您可能想要使用的文件路径。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 2010-10-13
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 2021-03-31
    • 2013-06-14
    相关资源
    最近更新 更多