栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python日常用函数

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python日常用函数

保存文本文档函数
'''
file_path:创建文件的保存的位置
message:创建文件的内容
'''
def creat_file(file_path, message):
    f = open(file_path, mode='a', encoding=('utf-8'))
    f.write(message)
    f.write('n')
    f.close()

'''

例如:
message= '创建文本文件'
creat_file(r"C:UsersAdministratorDesktopmessage.txt",message)

'''

截取想要的中间字符串
'''
从一个字符串中截取中间需要的部分
content:字符串
startStr:开始位置
endStr:结束位置
'''

def GetMiddleStr(content, startStr, endStr):
    startIndex = content.index(startStr)
    if startIndex >= 0:
        startIndex += len(startStr)
    endIndex = content.index(endStr)
    return content[startIndex:endIndex]

'''
例如:
html = '从一个字符串中截取中间需要的部分'
text = GetMiddleStr(html,'一个','中')
print(text)   #  字符串
'''

链接下载图片
'''
url:图片下载链接地址
file_path:图片保存路径
file_name:图片名字
'''
import os,requests
def GetPicture(url,file_path,file_name):
    File_Name = file_path + file_name + ".jpg"
    try:
        if not os.path.exists(file_path):
            os.mkdir(file_path)
        if not os.path.exists(File_Name):
            th = requests.get(url)
            with open(File_Name, "wb") as f:
                f.write(th.content)
                f.close()
                print("文件保存成功")
        else:
            print("文件已经存在")
    except:
        print("下载失败")


'''
例如:
url2 = ['https://gimg2.baidu.com/image_search/src=https://www.mshxw.com/skin/sinaskin/image/nopic.gif']
root = r"C:UsersAdministratorDesktop "
title2 = ['阿狸','阿猫']
for url3 in url2:
    for title in title2:
        GetPicture(url3,root,title)

'''
 把ISO-8859-1编码转化为UTF-8

def ZM(string):
    ISO = string.encode('ISO-8859-1') #先编码
    return ISO.decode('utf-8')# 再解码

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/269688.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号