gpt4 book ai didi

python - Robot Framework 中包含子目录的 Zip 目录

转载 作者:太空狗 更新时间:2023-10-30 00:05:21 28 4
gpt4 key购买 nike

使用 Robot Framework,我试图压缩一个包含一个文件的目录和三个包含文件的子目录。我正在使用 ArchiveLibrary和关键字从目录中的文件创建 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。

最佳答案

编辑:当使用 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()

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

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

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

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

关于python - Robot Framework 中包含子目录的 Zip 目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42995992/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com