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

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为textview创建选定状态(突出显示)   Java Hibernate计数行   Java语言中的字符串比较   java为什么SparkLauncher会立即返回而不会生成任何作业?   java layout_centerInParent在抛出回收视图后不工作   c#中的readInt16()与java中的readShort()   java如何在工具栏菜单中添加昼夜切换器   java在eclipse上向Tomcat提供<Realm/>信息   java使用给定的随机路径构造一个图   带有对象推送的java Morphia聚合阶段组   java关闭JTable实例   性能如何更好地转换java中的所有集合元素?   JAVA木卫一。IOException:通过Eclipse读取Java中的EOF Lucene   java如何在Android中将光标设置在tableLayout的行/列中所需的位置   使用HashMap的Set的java迭代器不会生成值/键吗?   java google guava cachebuilder在ExipeAfterAccess和expireActerWrite之间使用的时间更长   如何将这个排序映射方法从java转换为Kotlin   java如何从运行的JAR文件中读取war目录?   SpringBootJava。使用Java 9模块(JPM)时lang.NoSuchMethodError