如何使用Python创建一个临时的文件或文件夹?

2026-05-16 18:060阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计1141个文字,预计阅读时间需要5分钟。

如何使用Python创建一个临时的文件或文件夹?

问题:在程序执行时需要创建一个临时文件或目录,并希望在文件或目录使用完毕后自动删除。解决方案:可以使用`tempfile`模块中的函数来创建一个匿名的临时文件,它会在文件不再使用时自动删除。

问题

你需要在程序执行时创建一个临时文件或目录,并希望使用完之后可以自动销毁掉。

解决方案

tempfile 模块中有很多的函数可以完成这任务。 为了创建一个匿名的临时文件,可以使用 tempfile.TemporaryFile

from tempfile import TemporaryFile with TemporaryFile('w+t') as f: # Read/write to the file f.write('Hello World\n') f.write('Testing\n') # Seek back to beginning and read the data f.seek(0) data = f.read() # Temporary file is destroyed

或者,如果你喜欢,你还可以像这样使用临时文件:

f = TemporaryFile('w+t') # Use the temporary file ... f.close() # File is destroyed

TemporaryFile() 的第一个参数是文件模式,通常来讲文本模式使用 w+t ,二进制模式使用 w+b

阅读全文

本文共计1141个文字,预计阅读时间需要5分钟。

如何使用Python创建一个临时的文件或文件夹?

问题:在程序执行时需要创建一个临时文件或目录,并希望在文件或目录使用完毕后自动删除。解决方案:可以使用`tempfile`模块中的函数来创建一个匿名的临时文件,它会在文件不再使用时自动删除。

问题

你需要在程序执行时创建一个临时文件或目录,并希望使用完之后可以自动销毁掉。

解决方案

tempfile 模块中有很多的函数可以完成这任务。 为了创建一个匿名的临时文件,可以使用 tempfile.TemporaryFile

from tempfile import TemporaryFile with TemporaryFile('w+t') as f: # Read/write to the file f.write('Hello World\n') f.write('Testing\n') # Seek back to beginning and read the data f.seek(0) data = f.read() # Temporary file is destroyed

或者,如果你喜欢,你还可以像这样使用临时文件:

f = TemporaryFile('w+t') # Use the temporary file ... f.close() # File is destroyed

TemporaryFile() 的第一个参数是文件模式,通常来讲文本模式使用 w+t ,二进制模式使用 w+b

阅读全文