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

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 ClientServersocket只能发送1个文件   使用jCUDA实现复杂矩阵的java操作   映射是否存在独立于持久性技术的Java数据API   java Android图像在ExiFinInterface不工作的情况下旋转   java api通过串口发送文件   java使用Restcontroller将空值转换为空字符串   如何在Java中指定网络接口   在一个不工作的安卓系统中,java在另一个文本视图的右边膨胀文本视图   Java JSON解析器错误   java单空间Swing文本   我在eclipse中制作的java游戏在导出后停止加载我的资产   java将给定字符串转换为long,并在解码时返回相同的字符串   java在安卓应用程序中使用dll库   javascript映射json对象并创建随机数组   java JMS主题生存时间   在Swing中的JTextArea上使用setText时出现java死锁   java JFXtra议程是否只在特定时间之间显示?