Python实用代码段收藏

本文最后更新于:3 个月前

点击获得封面头图

此文章使用CC-BY-NC协议,协议详情介绍请看此文


判断文件是否存在,不存在则执行特定指令:

1
2
3
4
5
6
7
import os

filename = 'thdbd.txt'
if not os.path.exists(filename): //若不存在"thdbd.txt"
os.system("touch thdbd.txt") //创建"thdbd.txt"
with open('thdbd.txt', 'w') as f:
f.write("thdbd") //写入内容

以cookie的格式打开文件并作为变量:

1
2
3
4
5
f=open(r'cookie.txt','r')
cookies={}
for line in f.read().split(';'):
name,value=line.strip().split('=',2)
cookies[name]=value

强制退出程序:

1
2
3
import sys

sys.exit(1)

更换工作目录:

1
2
3
import os

os.chdir("path/to/your/files")

检测是否安装了模块并尝试导入:

1
2
3
4
5
try:
import name
pass
except ImportError:
print("没有安装模块")

检测操作系统:

1
2
3
4
5
import platform
if platform.system() == 'Windows':
pass
else:
print("系统为:" + platform.system())

requests实现的更新方式:

1
2
3
4
5
url = "https://raw.githubusercontent.com/xxx.py"  #远端更新地址
r = requests.get(url)
with open('name.py', 'w') as f: #远端和本地文件名需一致
f.write(r.text)
print("更新完毕!")