在列表、不同子文件夹中存储丢失的文件后无法下载文件,Python

Fail to download files after storing missing files in list, in different subfolders, Python

我正在尝试为服务器脚本创建一个函数,以便能够自动检查脚本按预期工作所需的某些依赖项,方法是首先检查文件系统中是否存在文件,如果不存在,则获取它们来自网络服务器。但我无法真正弄清楚如何进行。该函数如下所示:

folder1 = "Folder1/"
folder2 = "Folder1/Folder2/"

def downloadTxt():
    import os.path
    import requests
    file_repository = "https://ourserver.tld/txtfiles/"
    folderlist = [folder1, folder2]
    for folder in folderlist:
        missing_folders = []
        if not os.path.exists(folder):
            missing_folders.append(folder)
        for folder in missing_folders:
            os.makedirs(folder, exist_ok=True)
            
    filelist = [
        folder1 + "example1.txt",
        folder2 + "example2.txt",
        folder2 + "example3.txt",
        folder2 + "example4.txt",
        ]  # Etc.. I have tons of these files but not really anything useful to show here
    for file in filelist:
        missing_files = []
        if not os.path.exists(file):
            missing_files.append(file)
        for file in missing_files:
            r = requests.get(file_repository + file)
            open(file, "wb").write(r.content)
f_auto_download_txt()

这实际上会在正确的文件夹中创建根据文件列表命名的文件,但内容只是 HTML 错误消息:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL was not found on this server.</p>
</body></html>

如果我检查网络服务器日志,我可以看到它实际上试图从 /webfolder/webfolder/file 获取文件,因为文件列表的结构,这是有道理的。

[28/Oct/2021:05:18:30 +0200] "GET /Folder1/Folder1/example1.txt HTTP/1.1" 404 2804 "-" "python-requests/2.26.0"

我试图“让它工作”,即使它很难看

    missing_files_folder1_stripped = [s.replace(folder1, "") for s in missing_files]
    missing_files_folder2_stripped = [s.replace(folder2, "") for s in missing_files]
    missing_files_all_stripped = missing_files_folder1_stripped + missing_files_folder2_stripped
    for file in missing_files_all_stripped:
        r = requests.get(file_repository + file)
        open(file, "wb").write(r.content)

但没有成功,我设法获取了一个应该在 Folder1 中的文件,下载到根目录,当它到达 Folder2 中的第一个文件时,我得到“找不到 Folder2\example2.txt。服务器甚至给了我一个 HTTP 代码 200,所以它看起来应该可以工作,但没有。所以我的另一个计划是将所有文件下载到任何目录,然后对其进行排序,但现在我'我什至无法正确下载文件。

如果有任何可行的解决方案,请提前致谢!

在更好地检查网络服务器的访问日志后,我最终解决了这个问题,寻找脚本实际要求的文件,我发现文件结构中仍然有一些错误。我最终做的是创建一个新的、“干净”的文件列表,其中删除了 Folder1,并更改了打开函数的参数,所以现在它按预期工作了。

    new_list_clean = [s.replace(folder1, "") for s in missing_files]
    
    for file in new_list_clean:
        r = requests.get(file_repository + file)
        open(folder1 + file, "wb").write(r.content) 

它也可能会或可能不会给你一个权限错误,在我的例子中,我只是确保对我的测试机器上的那个文件夹有写访问权限(运行 的 Windows), 但设置

可能会有用
os.makedirs(folder, exist_ok=True, mode=0760)  # Example for giving fileowner full access and group read+write

立即避免在 *nix 系统上出现此问题。