tempfile模块的作用

主要是创建临时目录,存放临时数据,关闭时,临时文件则删除处理

 1、手动创建临时文件与filetemp模块创建临时文件的比较

import os
import tempfile

print('创建一个PID的文件名')
filename = 'temp/guess_my_name.{}.txt'.format(os.getpid())

# 手动创建临时文件,并且获取文件名
with open(filename, 'w+b') as temp:
    print('temp:')
    print('   {!r}'.format(temp))
    print('temp.name:')
    print('   {!r}'.format(temp.name))

os.remove(filename)

# 利用tempfile模块创建临时文件,并且获取文件名
print('\nTemporaryFile:')
with tempfile.TemporaryFile() as temp:
    print('temp:')
    print('   {!r}'.format(temp))
    print('temp.name')
    print('   {!r}'.format(temp.name))
tempfile_TemporaryFile.py

相关文章:

  • 2021-06-25
  • 2021-12-15
  • 2022-12-23
  • 2021-09-19
  • 2022-01-01
  • 2021-06-09
  • 2021-12-14
猜你喜欢
  • 2021-11-27
  • 2021-11-12
  • 2022-12-23
  • 2022-12-23
  • 2021-12-06
相关资源
相似解决方案