保存文件时如何避免保存子文件夹?

How to avoid saving subfolders when saving a file?

该函数创建一个文件夹并将文件保存到其中。然后将文件夹打包成rar压缩包发送给用户,之后新建的文件夹和压缩包从服务器上删除。

code.py

new_file_name = self.generate_file_name(rfi, vendor, current_scoring_round)

path_to_temp_folder = os.path.dirname(BASE_DIR)
if not os.path.exists(f'{path_to_temp_folder}/temp_folder'):
    pathlib.Path(f'{path_to_temp_folder}/temp_folder').mkdir(parents=True, exist_ok=True)

wb.save(f'{path_to_temp_folder}/temp_folder/{new_file_name}') #save xlsx file from openpyxl library

archive = self.generate_zip_name(rfi) # generate name for archive

to_rar = f'{path_to_temp_folder}/temp_folder'
patoolib.create_archive(archive, (to_rar,))  # patoolib - to .rar converter 

to_download = f'{path_to_temp_folder}/{archive}'

if os.path.exists(to_download):
try:
    with open(to_download, 'rb') as fh:
        response = HttpResponse(fh.read(),
                                content_type="content_type='application/vnd.rar'")
        response['Content-Disposition'] = 'attachment; filename= "{}"'.format(archive)
        return response
finally:
    shutil.rmtree(to_rar, ignore_errors=True)
    default_storage.delete(to_download)

一切正常,但问题是下载的存档包含子文件夹 - 保存文件的路径。

预期结果:

folder.rar
    file.xlsx

实际结果:

folder.rar
    /home
        /y700
            /projects
                file.xlsx

patool 的文档很少。这似乎表明这应该可以通过在 create-archive 命令中传递文件路径来实现。不过我试过了,好像不行。

所以唯一的选择可能是将工作目录更改为 test.xlsx 文件的位置:

import patoolib
import os

new_file_name = self.generate_file_name(rfi, vendor, current_scoring_round)

path_to_temp_folder = os.path.dirname(BASE_DIR)
if not os.path.exists(f'{path_to_temp_folder}/temp_folder'):
    pathlib.Path(f'{path_to_temp_folder}/temp_folder').mkdir(parents=True, exist_ok=True)

wb.save(f'{path_to_temp_folder}/temp_folder/{new_file_name}') #save xlsx file from openpyxl library

archive = self.generate_zip_name(rfi) # generate name for archive

to_rar = f'{path_to_temp_folder}/temp_folder'

cwd=os.getcwd()
os.chdir('to_rar')
patoolib.create_archive(cwd+archive, ({new_file_name},))  # patoolib - to .rar converter     
os.chdir('cwd')

to_download = f'{path_to_temp_folder}/{archive}'

if os.path.exists(to_download):
try:
    with open(to_download, 'rb') as fh:
        response = HttpResponse(fh.read(),
                                content_type="content_type='application/vnd.rar'")
        response['Content-Disposition'] = 'attachment; filename= "{}"'.format(archive)
        return response
finally:
    shutil.rmtree(to_rar, ignore_errors=True)
    default_storage.delete(to_download)

这在我的系统上有效,例如,我在存档中得到一个文件(使用 tar,因为我没有安装 rar):

import patoolib
import os

cwd=os.getcwd()
os.chdir('foo/bar/baz/qux/')
patoolib.create_archive(cwd+'/foo.tar.gz',('test.txt',))
os.chdir(cwd)

请注意,您应该真正使用 os.path.join 而不是连接字符串,但这只是一个快速而肮脏的测试。