如何使wget-python模块不下载副本?

2024-04-28 23:32:01 发布

您现在位置:Python中文网/ 问答频道 /正文

当试图从4chan上的post(通过BASC\u py4chan)下载一个文件并通过wget下载它时,wget会下载这个文件,即使我做了一个if语句说如果文件名与当前目录中的文件名相同就不要下载它?这是wget python的问题还是我犯了错误?你知道吗

    if 'ylyl' in subject or 'YLYL' in subject:
    for post in thread.all_posts:
        if post.has_file:
            print(post.filename)
            for filename in os.listdir(cwd):
                print(filename)
                if filename != post.filename:
                    url = post.file_url
                    wget.download(url)
                    time.sleep(1.03)

Tags: 文件inurlforif文件名语句wget
2条回答

我发现你的代码有问题。问题就在这一点上:

    for filename in os.listdir(cwd):
        print(filename)
        if filename != post.filename:
            url = post.file_url
            wget.download(url)
            time.sleep(1.03)

您正在遍历目录中的每个文件。这意味着,如果目录中有一个文件名与post的文件名不同,它将被下载。你知道吗

假设您的代码试图下载file3,而您的目录包含file1、file2和file3。你知道吗

对于目录中的那些文件,if语句将进行这3个检查。你知道吗

        if 'file1' != 'file3':
            url = post.file_url
            wget.download(url)
            time.sleep(1.03)

        if 'file2' != 'file3':
            url = post.file_url
            wget.download(url)
            time.sleep(1.03)

        if 'file3' != 'file3':
            url = post.file_url
            wget.download(url)
            time.sleep(1.03)

您可能想要尝试的是检查文件名是否在操作系统列表目录()返回。你知道吗

以下是我的解决方案:

if 'ylyl' in subject or 'YLYL' in subject:
for post in thread.all_posts:
    if post.has_file:
        print(post.filename)
        if post.filename not in os.listdir(cwd):
            url = post.file_url
            wget.download(url)
            time.sleep(1.03)

我想你可以把密码改成

if 'ylyl' in subject or 'YLYL' in subject:
    for post in thread.all_posts:
        if post.has_file:
        print(post.filename)
        # changed at here
        if post.filename not in os.listdir(cwd):
            url = post.file_url
            wget.download(url)
            time.sleep(1.03)

相关问题 更多 >