【问题标题】:Problem when adding multiple files from list [duplicate]从列表中添加多个文件时出现问题[重复]
【发布时间】:2021-01-20 13:45:20
【问题描述】:

我的问题是我有太多需要附加的 torrent 文件。我把它们都列在一个列表中。

torrent_list = ['file1.torrent', 'file2.torrent', etc.......]

按文件下载种子:

torrent_file = open('my-torrent-file.torrent', 'rb')
qb.download_from_file(torrent_file)

使用文件下载多个种子:

如果不手动编写它,我无法让它工作,就像示例中显示的那样。 我想从列表中加载它们。有人可以帮忙吗?

torrent_file_list = [open('1.torrent', 'rb'), open('2.torrent', 'rb')]
qb.download_from_file(torrent_file_list)

【问题讨论】:

    标签: python


    【解决方案1】:

    使用列表推导式。

    torrent_file_list = [open(filename, 'rb') for filename in torrent_list])
    qb.download_from_file(torrent_file)
    for f in torrent_file_list:
        close(f)
    

    【讨论】:

    • 当涉及到函数open 时,您必须在上下文管理器中使用它,因此文件最后会关闭。如果你不关闭文件,那么它可能会破坏它。在此示例中,您没有关闭文件
    • 相信垃圾回收器会自动关闭这种情况下的文件。
    • 你是对的。我搜索了一下,好像和你说的一样。已解释 here 抱歉?,谢谢,我不知道。
    • 您说得对,通常最好显式打开和关闭或使用上下文管理器。但为此,这样做更简单。
    • 所以它仍然不适合我。回溯(最后一次调用):文件“D:\torrents\src\torrenthooker.py”,第 15 行,在 qb.download_from_file([open(torrent_list, 'rb') for filename in torrent_list]) 文件“ D:\torrents\src\torrenthooker.py", line 15, in qb.download_from_file([open(torrent_list, 'rb') for filename in torrent_list]) TypeError: expected str, bytes or os.PathLike object,不列出
    【解决方案2】:

    试试这样:

    torrent_list = ['file1.torrent', 'file2.torrent']
    for myFile in torrent_list:
      with open(myFile,'rb') as torr:
        qb.download_from_file(torr)
    

    【讨论】:

    • 所以,这种方法有效,但一段时间后它就坏了。通过这个例子a,它能够将 116 个 torrent 文件加载到我的 torrent 客户端,然后它就坏了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 2018-03-07
    • 1970-01-01
    • 2021-07-29
    • 2019-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多