2017-03-24 34 views
5

使用Robot Framework,我试图用一个文件和三个包含文件的子目录压缩目录。我正在使用ArchiveLibrary和关键字“从目录中的文件创建邮编”。结果是一个压缩目录包含顶部目录中的一个文件和三个空的子文件夹。与Robot Framework中的子目录的Zip目录

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

这是怎样的关键字最初定义:

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。

回答

3

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

创建焦油的关键词是一个有点不同 - 默认情况下它包括子目录中的文件,现在你有一个选项不:

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

编辑:保留子目录结构文件在 - 子目录中。 生成的文件是顶层目标目录,及其所有子目录 - 它下面的(而不是归档保存的完整路径目标目录)

arcnameargument controls什么是存储在一个文件的名称在档案中 - 并通过第7行,我们保留相对目录和文件名。

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

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

+0

谢谢!这使我更加靠近了一点,但并没有像预期的那样工作。现在我得到所有文件,但是子目录被删除。 为了使机器人脚本工作,我需要保持目录的确切结构(OT:因为实际的测试是通过验证脚本运行压缩目录,其中测试变体是要更改XML文件中的数据放置在压缩目录中) 子目录和结构是否也包含在内? – Sabotchick

+0

那么,“这会教我发布无线运行”:) JK,编辑了包含该部分的答案 - 另外还清理了一些并非真正需要的代码。 HTH – Todor

+0

太棒了,就是我想要的!谢谢! :) – Sabotchick