加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 在Robot Framework中包含子目录的Zip目录

发布时间:2020-12-16 22:42:40 所属栏目:Python 来源:网络整理
导读:使用Robot Framework,我正在尝试使用一个文件和三个包含文件的子目录来压缩目录.我正在使用ArchiveLibrary和关键字在目录中创建Zip From Files.结果是一个压缩目录,其中包含顶层目录中的一个文件和三个空子文件夹. 如何调整库以便包含子文件夹的内容? 这是

使用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()

Link到完整的图书馆.

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

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

Zip xml file
    ${zipfilename}=    set variable    komplett.zip
    Create zip from Files in directory    ../xml/komplett/  ${zipfilename}

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

最佳答案
编辑:当使用库版本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}

创建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}

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()

编辑:保留 – 子目录中文件的子目录结构.
生成的文件位于顶级目标目录及其所有子目录(位于其下方(与保留目标目录的完整路径的存档相对))

arcname argument controls什么是存档中存储的文件的名称 – 通过第7行,我们保留了相对目录和文件名.

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读