带有子目录的Zip目录在Robot Framework中

Sab*_*ick 6 python robotframework

使用Robot Framework,我正在尝试使用一个文件和三个包含文件的子目录来压缩目录.我正在使用ArchiveLibrary和关键字在目录中创建Zip From Files.结果是一个压缩目录,其中包含顶层目录中的一个文件和三个空子文件夹.

如何调整库以便包含子文件夹的内容?

这是关键字最初定义的方式:

def create_zip_from_files_in_directory(self, directory, filename):

    ''' Take all files in a directory and create a zip package from them
    `directory` Path to the directory that holds our files
    `filename` Path to our destination ZIP package.
    '''

    if not directory.endswith("/"):
        directory = directory + "/"
    zip = zipfile.ZipFile(filename, "w")
    files = os.listdir(directory)
    for name in files:
        zip.write(directory + name, arcname=name)
    zip.close()
Run Code Online (Sandbox Code Playgroud)

链接到完整的库.

我一直在尝试os.walk,没有成功.

如何在.robot文件中使用关键字:

Zip xml file
    ${zipfilename}=    set variable    komplett.zip
    Create zip from Files in directory    ../xml/komplett/  ${zipfilename}
Run Code Online (Sandbox Code Playgroud)

如果它有所不同,我真的只需要解决这个特定情况,而不是一般情况,这意味着我不介意输入每个目录的路径,然后以某种方式加入,我只是不明白该怎么做...另外,我使用PyCharm作为编辑器,而不是RIDE.

Tod*_*kov 5

编辑:使用 0.4 及更高版本的库时,您可以选择是否应包含子目录。例如:

Create Zip From Files In Directory    ../xml/komplett/  no_sub_folders.zip
Create Zip From Files In Directory    ../xml/komplett/  dir_and_sub_folders.zip   sub_directories=${true}
Run Code Online (Sandbox Code Playgroud)

创建 tar 的关键字有点不同 - 默认情况下它包含子目录中的文件,现在您可以选择不:

Create Tar From Files In Directory    ../xml/komplett/  dir_and_sub_folders.tar 
Create Tar From Files In Directory    ../xml/komplett/  no_sub_folders.tar   sub_directories=${false}
Run Code Online (Sandbox Code Playgroud)

的默认值sub_directories基于预先存在的行为,不会破坏测试用例中的现有用法。


原始答案,对于版本 < 0.4:

如果您愿意修补库,则此代码应执行以下操作:

zip = zipfile.ZipFile(filename, "w")
for path, _, files in os.walk(directory):
    for name in files:
        file_to_archive = os.path.join(path, name)

        # get rid of the starting directory - so the zip structure is top-level starting from it
        file_name = path.replace(directory, '')
        file_name = os.path.join(file_name, name)

        zip.write(file_to_archive, arcname=file_name) # set the desired name in the archive by the arcname argument
zip.close()
Run Code Online (Sandbox Code Playgroud)

编辑:保留子目录中文件的子目录结构。生成的文件与顶级目标目录及其所有子目录 - 在其下方(与保留目标目录完整路径的存档相反)

arcname 参数控制什么是存储在归档文件的名称-并通过线7条,我们保持相对目录以及文件名。

总是使用os.path.join因为它会自动处理不同文件系统(ntfs/linux/etc)中的差异。

如果最终解决方案适合您,请不要忘记向库所有者提出补丁 - 回馈社区:)