-
python入门教程之Python3标准库:tempfile临时文件系统对象(2)
本站最新发布 Python从入门到精通|Python基础教程
试听地址 https://www.xin3721.com/eschool/pythonxin3721/
temp: {!r}'.format(temp))
for i in range(3):
temp.write('This line is repeated over and over.\n')
print(temp._rolled, temp._file)
print('rolling over')
temp.rollover()
print(temp._rolled, temp._file)
试听地址 https://www.xin3721.com/eschool/pythonxin3721/
temp: {!r}'.format(temp))
在这个例子中,由于缓冲区非常大,远远大于实际的数据量,所以除非调用rollover(),否则不会在磁盘上创建任何文件。
1.4 临时目录
需要多个临时文件时,可能更方便的做法是用TemporaryDirectory创建一个临时目录,并打开该目录中的所有文件。
- import pathlib
- import tempfile
- with tempfile.TemporaryDirectory() as directory_name:
- the_dir = pathlib.Path(directory_name)
- print(the_dir)
- a_file = the_dir / 'a_file.txt'
- a_file.write_text('This file is deleted.')
- print('Directory exists after?', the_dir.exists())
- print('Contents after:', list(the_dir.glob('*')))
上下文管理器会生成目录名,可以在上下文块中用来建立其他文件名。
1.5 临时文件位置
如果没有使用dir参数指定明确的目标位置,则临时文件使用的路径会根据当前平台和设置而变化。tempfile模块包括两个函数来查询运行时使用的设置。
- import tempfile
- print('gettempdir():', tempfile.gettempdir())
- print('gettempprefix():', tempfile.gettempprefix())
gettempdir()返回包含所有临时文件的默认目录,gettempprefix()返回新文件和目录名和字符串前缀。
gettempdir()返回的值根据一个简单算法来设置,它会查找一个位置列表,寻找第一个允许当前进程创建文件的位置。
- import tempfile
- tempfile.tempdir = '/I/changed/this/path'
- print('gettempdir():', tempfile.gettempdir())
如果程序需要对所有临时文件使用一个全局位置,但不使用以上任何环境变量,则应当直接设置tempfile.tempdir,为该变量赋一个值。
栏目列表
最新更新
如何使用OS模块中的stat方法
Python os 模块
seek() 方法
python打开文件实例1
Python写入文件
什么是流?
文件操作如何进制逐行读取
Python相对路径
with创建临时运行环境
Python文件操作
.Net Standard(.Net Core)实现获取配置信息
Linux PXE + Kickstart 自动装机
Shell 编程 基础
Shell 编程 条件语句
CentOS8-网卡配置及详解
Linux中LVM逻辑卷管理
1.数码相框-相框框架分析(1)
Ubuntu armhf 版本国内源
Linux中raid磁盘阵列
搭建简易网站
access教程之Access简介
mysql 安装了最新版本8.x版本后的报错:
Mysql空间数据&空间索引(spatial)
如何远程连接SQL Server数据库的图文教程
复制SqlServer数据库的方法
搜索sql语句
sql中返回参数的值
sql中生成查询的模糊匹配字符串
数据定义功能
数据操作功能