python文件和zip操作变得简单
flametree的Python项目详细描述
flametree是一个python库,它提供了处理文件和文件夹的简单语法 (没有os.path.join,os.listdir等),并且对不同的文件系统使用相同的方法。
编写一个flametree程序来读/写磁盘文件夹中的文件,您的代码也将 能够读取/写入ZIP存档和虚拟(内存)存档-这是特别 在Web服务器上很有用。
例如,下面是如何使用flametree读取文件texts/poems/the_raven.txt,全部替换 文本中出现“海鸥”所指的“乌鸦”一词,并将结果写入一个新的 同一文件夹中的文件the_seagull.txt:
fromflametreeimportfile_treewithfile_tree("texts")asroot:poem_text=root.poems.the_raven_txt.read()new_text=poem_text.replace("raven","seagull")root.poems._file("the_seagull.txt").write(new_text)
即使在这个非常简单的用例中,语法也比os方式更清晰, 其内容如下:
importoswithopen(os.path.join("poems","the_raven.txt"),"r")asf:poem_text=f.read()new_text=poem_text.replace("raven","seagull")withopen(os.path.join("poems","the_seagull.txt"),"w")asf:content=f.write(new_text)
此外,相同的flametree代码也适用于zip归档文件中的文件:
withfile_tree("my_archive.zip")asroot:poem_text=root.poems.the_raven_txt.read()new_text=poem_text.replace("raven","seagull")root.poems._file("the_seagull.txt").write(new_text)
现在处于硬模式:假设您的服务器接收 包含poems/the_raven.txt的存档,并且必须返回一个新的zip 包含文件poems/the_seagull.txt。在这里,核心的语法 操作相同:
destination_zip=file_tree("@memory")# Create a new virtual zipwithfile_tree(the_raven_zip_data)asroot:poem_text=root.poems.the_raven_txt.read()new_text=poem_text.replace("raven","seagull")destination_zip._dir("poems")._file("the_seagull.txt").write(new_text)destination_zip_data=destination_zip._close()# Now send the data to the client
有关更多示例和功能,请参见下面的usage部分。
信息
pip安装:
pip install flametree
github页
https://github.com/Edinburgh-Genome-Foundry/Flametree
许可证:麻省理工学院,爱丁堡基因组铸造厂版权所有