tempfile:让你 Python 代码轻松无痕的运行

大家好,我们知道软件运行过程中一般会在指定位置生成临时文件,这些资源不要轻易删除,可能是过程文件,定时清理是必要的,今天给大家分享一款工具:tempfile,喜欢本文点赞支持,欢迎收藏学习,文末提供技术交流群。

一、简介

这里介绍python中临时文件及文件夹使用。

使用的是tempfile包:

pip install tempfile

https://docs.python.org/3/library/tempfile.html

二、临时文件夹

2.1 获取临时文件夹

# 获取临时文件夹
tmpdir = tempfile.gettempdir()
print(tmpdir) #/tmp

2.2 生成临时文件夹

# 方式一:生成默认临时文件夹
tmpdir = tempfile.mkdtemp()
print(tmpdir) #/tmp/tmpui77cgud

# 方式二:生成自定义临时文件夹(指定前缀、后缀、目录,可指定其中一部分),suffix:后缀, prefix:前缀, dir:目录

tmpdir = tempfile.mkdtemp(suffix='_txt', prefix='tp_dir_', dir='/home/tmp/py_rs_file')

print(tmpdir) # /home/tmp/py_rs_file/tp_dir_06l_o2dm_txt

三、临时文件

3.1 生成不自动删除(关闭时)的临时文件

# 方式一:生成默认临时文件,默认为二进制文件

tmpfile = tempfile.mkstemp()[1]
print(tempfile) #/tmp/tmp75kazf_8
# 数据写入
with open(tmpfile, 'w+') as t_f:
    t_f.writelines('hello world')

# 方式二:生成自定义临时文件(指定前缀、后缀、目录、文件类型参数,可指定其中一部分),suffix:后缀, prefix:前缀, dir:目录, text:文件类型,True为文本,false为二进制

tmpfile = tempfile.mkstemp(suffix='.txt', prefix='tp_', dir='/home/tmp/py_rs_file', text=True)[1]
print(tempfile) # /home/tmp/py_rs_file/tp_pn2973g0.txt

# 数据写入
with open(tmpfile, 'w+') as t_f:
    t_f.writelines('hello world')

3.2 生成自动删除的临时文件

# 方式一:创建临时文件,文件关闭时自动删除
tmpfile = tempfile.TemporaryFile(mode='w+t')
tmpfile.write('hello world') ##数据写入
tmpfile.seek(0)
tmpTxt = tmpfile.read() #数据读取
print(tmpTxt)
tmpfile.close() #关闭时文件自动删除

# 方式二:创建临时文件,文件关闭时根据delete参数确定是否自动删除, True:删除  False:不删除
with tempfile.NamedTemporaryFile(delete=False) as tmpfile:
    file_name = tmpfile.name
    print(file_name) #/tmp/tmp73zl8gmn
    tmpfile.write('hello world'.encode())
    tmpfile.seek(0)
    tmpTxt = tmpfile.read().decode()
    print(tmpTxt)

# 方式三:创建自定义临时文件,文件关闭时可根据delete参数确定是否自动删除, True:删除  False:不删除
# 其他配置参数有,mode:文件模式(w+b为二进制模式(默认),w+t为文本模式),suffix:后缀, prefix:前缀, dir:目录
with tempfile.NamedTemporaryFile(mode='w+t', suffix='.txt', prefix='tp_', dir='/home/tmp/py_rs_file',delete=False) as tmpfile:
    file_name = tmpfile.name
    print(file_name) #/home/tmp/py_rs_file/tp_fcwpmh3l.txt
    tmpfile.write('hello world')
    tmpfile.seek(0)
    tmpTxt = tmpfile.read()
    print(tmpTxt)

根据具体情况,临时资源可以直接调用内存或数据库存储。


技术交流

欢迎转载、收藏、有所收获点赞支持一下!

在这里插入图片描述

目前开通了技术交流群,群友已超过2000人,添加时最好的备注方式为:来源+兴趣方向,方便找到志同道合的朋友

  • 方式①、发送如下图片至微信,长按识别,后台回复:加群;
  • 方式②、添加微信号:dkl88191,备注:来自CSDN
  • 方式③、微信搜索公众号:Python学习与数据挖掘,后台回复:加群

长按关注

import subprocess import time from playwright.sync_api import sync_playwright class Zzb(object): def __init__(self, number=1): self.page = None path = r"C:\Program Files\Google\Chrome\Application\chrome.exe" params = "--remote-debugging-port=9222" cmd = f'"{path}" {params}' subprocess.Popen(cmd, shell=True) self.number_ = number time.sleep(1) def main(self): with sync_playwright() as p: browser = p.chromium.connect_over_cdp("http://localhost:9222") context = browser.contexts[0] self.page = context.pages[0] if context.pages else context.new_page() js = "Object.defineProperties(navigator, {webdriver:{get:()=>false}});" self.page.add_init_script(js) self.run_spider() self.page.close() def run_spider(self): self.page.goto('https://www.jd.com/') if __name__ == '__main__': zzb = Zzb() zzb.main()为啥会报错DevTools remote debugging requires a non-default data directory. Specify this using --user-data-dir. Traceback (most recent call last): File "D:\python\PyCharm 2023.2.5\pythonProject\playwright模板.py", line 35, in <module> zzb.main() File "D:\python\PyCharm 2023.2.5\pythonProject\playwright模板.py", line 19, in main browser = p.chromium.connect_over_cdp("http://localhost:9222") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\python\Lib\site-packages\playwright\sync_api\_generated.py", line 14887, in connect_over_cdp self._sync( File "D:\python\Lib\site-packages\playwright\_impl\_sync_base.py", line 115, in _sync return task.result() ^^^^^^^^^^^^^ File "D:\python\Lib\site-packages\playwright\_impl\_browser_type.py", line 188, in connect_over_cdp response = await self._channel.send_return_as_dict("connectOverCDP", params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\python\Lib\site-packages\playwright\_impl\_connection.py", line 67, in send_return_as_dict return await self._connection.wrap_api_call( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\python\Lib\site-packages\playwright\_impl\_connection.py", line 528, in wrap_api_call raise rewrite_error(error, f"{parsed_st['apiName']}: {error}") from None playwright._impl._errors.Error: BrowserType.connect_over_cdp: connect ECONNREFUSED ::1:9222 Call log: - <ws preparing> retrieving websocket url from http://localhost:9222
最新发布
05-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值