用于管理临时文件和目录的上下文管理器。

temporar的Python项目详细描述


CompatibilityImplementationsFormatDownloads

用于管理临时文件和目录的上下文管理器。

withtemporary.temp_dir()asd:...withtemporary.temp_file(content='hello')asf:...

安装:

$ pip install temporary

临时目录示例

在进入上下文管理器时创建临时目录,并且 退出时删除:

>>>importtemporary>>>withtemporary.temp_dir()astemp_dir:...asserttemp_dir.is_dir()>>>assertnottemp_dir.exists()

这次让我们将临时目录设为工作目录:

>>>importos>>>withtemporary.temp_dir(make_cwd=True)astemp_dir:...assertstr(temp_dir)==os.getcwd()>>>assertnotstr(temp_dir)==os.getcwd()

后缀、前缀和父目录选项将传递给标准 tempfile.mkdtemp()函数:

>>>withtemporary.temp_dir()asp:...withtemporary.temp_dir(suffix='suf',prefix='pre',parent_dir=p)asd:...assertd.parent==p...assertd.name.startswith('pre')...assertd.name.endswith('suf')

此函数还可以用作装饰器,其in_temp_dir别名为:

>>>@temporary.in_temp_dir()...defmy_function():...assertold_cwd!=os.getcwd()...>>>old_cwd=os.getcwd()>>>my_function()>>>assertold_cwd==os.getcwd()

临时文件示例

在进入上下文管理器和 退出时删除。

>>>importtemporary>>>withtemporary.temp_file()astemp_file:...asserttemp_file.exists()>>>assertnottemp_file.exists()

用户还可以为要填充的文件提供一些内容:

>>>withtemporary.temp_file('hello!')astemp_file:...withtemp_file.open()asf:...assertf.read()=='hello!'

临时文件可以放在自定义目录中:

>>>withtemporary.temp_dir()astemp_dir:...withtemporary.temp_file(parent_dir=temp_dir)astemp_file:...asserttemp_file.parent==temp_dir

如果出于某种原因,用户希望在 退出上下文,也没关系:

>>>withtemporary.temp_file()astemp_file:...temp_file.unlink()

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java如何提高我的软件项目的速度?   java将Jetty嵌入JavaSE项目   数组中的java重复字符   java我的Shell排序没有按预期工作,我需要一些帮助来找出我做错了什么   java如何在JBoss EAP6/AS7中应用先过滤后安全约束   java使用一个随机运算符来处理多个变量   java为什么我不能在文件中写我的二叉树?   java应用程序不会在Eclipse emulator上运行   我第一次尝试制作一个简单的基于瓷砖的java游戏   java为TermVectors安装Solr修补程序   java无法将更新的对象值从客户端发送到服务器,服务器读取不存在的值   Azure,java sdk,使用ARM模板部署无法转换参数文件   是否有一个Java等价于空合并运算符(?)在C#?   java如果只初始化了超类对象,是否可以调用特定于子类的方法?   向类文件传递值时出现java NullPointerException   java模不起作用   java Android TranslateAnimation动态更新布局的大小   数据结构如何在java中实例化队列对象?   java如果用户选择一些随机的相机应用程序,如何在安卓中正确处理相机意图?