Skip to main content

临时文件、目录

创建临时文件和目录

官方文档

Python提供了 tempfile 模块来便捷的创建临时文件和目录。

  • tempfile 可以在你程序运行时打开并存储临时的数据在文件或目录中。
  • tempfile 会在你程序停止运行后删除这些临时文件。

临时文件

from tempfile import  TemporaryFile

# 创建一个临时文件并为其写入一些数据
fp = TemporaryFile('w+t')
fp.write('Hello World!')

# 回到开始,从文件中读取数据
fp.seek(0)
data = fp.read()
print(data)

# 关闭文件,之后他将会被删除
fp.close()
# 临时文件现在已经被关闭和删除
with TemporaryFile('w+t') as fp:
fp.write('Hello universe!')
fp.seek(0)
fp.read()

这将创建一个临时文件并从中读取数据。 一旦读取文件的内容,就会关闭临时文件并从文件系统中删除。

tempfile 也可用于创建临时目录。

临时目录

import tempfile
import os

tmp = ''
with tempfile.TemporaryDirectory(
dir=r"W:\CPS\MyProject\python-tools\gis-api\static\upload", # 如果不指定dir,则在系统默认的临时目录创建
prefix="mikeio_", # 前缀
suffix=None, # 后缀
) as tmpdir:
print('Created temporary directory ', tmpdir)
tmp = tmpdir
print(os.path.exists(tmpdir))

print(tmp)
print(os.path.exists(tmp))

调用 tempfile.TemporaryDirectory() 会在文件系统中创建一个临时目录,并返回一个表示该目录的对象。

在上面的示例中,使用上下文管理器创建目录,目录的名称存储在 tmpdir 变量中。

第三行打印出临时目录的名称,os.path.exists(tmpdir) 来确认目录是否实际在文件系统中创建。 在上下文管理器退出上下文后,临时目录将被删除,并且对 os.path.exists(tmpdir)的调用将返回False,这意味着该目录已成功删除。

使用示例

python2.7

代码来自网络,在gis-api项目中用于调用arcpy模块使用过,没有什么大问题

from tempfile import mkdtemp

class TemporaryDirectory(object):
"""Create and return a temporary directory. This has the same
behavior as mkdtemp but can be used as a context manager. For
example:

with TemporaryDirectory() as tmpdir:
...

Upon exiting the context, the directory and everything contained
in it are removed.
"""

def __init__(self, suffix="", prefix="tmp", dir=None):
self._closed = False
self.name = None # Handle mkdtemp raising an exception
self.name = mkdtemp(suffix, prefix, dir)

def __repr__(self):
return "<{} {!r}>".format(self.__class__.__name__, self.name)

def __enter__(self):
return self.name

def cleanup(self, _warn=False):
if self.name and not self._closed:
try:
self._rmtree(self.name)
except (TypeError, AttributeError) as ex:
# Issue #10188: Emit a warning on stderr
# if the directory could not be cleaned
# up due to missing globals
if "None" not in str(ex):
raise
print(
"ERROR: {!r} while cleaning up {!r}".format(
ex,
self,
)
)
return
self._closed = True
if _warn:
self._warn("Implicitly cleaning up {!r}".format(self), ResourceWarning)

def __exit__(self, exc, value, tb):
self.cleanup()

def __del__(self):
# Issue a ResourceWarning if implicit cleanup needed
self.cleanup(_warn=True)

# XXX (ncoghlan): The following code attempts to make
# this class tolerant of the module nulling out process
# that happens during CPython interpreter shutdown
# Alas, it doesn't actually manage it. See issue #10188
_listdir = staticmethod(os.listdir)
_path_join = staticmethod(os.path.join)
_isdir = staticmethod(os.path.isdir)
_islink = staticmethod(os.path.islink)
_remove = staticmethod(os.remove)
_rmdir = staticmethod(os.rmdir)
_warn = _warnings.warn

def _rmtree(self, path):
# Essentially a stripped down version of shutil.rmtree. We can't
# use globals because they may be None'ed out at shutdown.
for name in self._listdir(path):
fullname = self._path_join(path, name)
try:
isdir = self._isdir(fullname) and not self._islink(fullname)
except OSError:
isdir = False
if isdir:
self._rmtree(fullname)
else:
try:
self._remove(fullname)
except OSError:
pass
try:
self._rmdir(path)
except OSError:
pass

使用

def main():
with TemporaryDirectory() as tmp_dir:
if not os.path.isdir(tmp_dir):
raise "Temporary directory can't not used"
else:
print("Work in Temporary directory path: %s" % tmp_dir)