python相关

python相关

一、文件相关操作

1. os.path.dirname 获取文件路径

print(os.path.dirname('W:Python_File	est.py'))
# 结果: W:Python_File

print(os.path.dirname('/a/b')
# 结果: /a

print(os.path.dirname('/a/b/'))
# 结果: /a/b

print(os.path.dirname(__file__))
# 输出当前执行文件所在的路径地址

2. os.path.join 文件路径拼接

file_path = os.path.join('/test','pdf','test.pdf')
# file_path = '/test/pdf/test.pdf'

3. os.path.exists 判断文件或文件夹是否存在

# 如果不存在文件夹,则创建
if not os.path.exists(dir_name)
   os.makedirs(dir_name)

4. os.makedirs 递归创建目录

如果目录已存在,则报错

5. open(file_name [, access_mode][, buffering]) 文件操作

  • 完整的文件操作
    open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
    • file: 必需,文件路径(相对或者绝对路径
    • mode: 可选,文件打开模式,包括只读r,只写w,读写w+,追加模式a+等
    • encoding: 一般使用utf-8
with open('./pdf/test.txt','a+',encoding='utf-8') as file:
	file.write('abc')

5-1. 文件操作的模式

模式 描述
r 已只读模式打开文件,指针在开头.默认模式
b 二进制模式
w 打开一个文件只用于写入,指针在开头.文件不存在则新建
w+ 读写,指针在开头,文件不存在则创建
r+ 读写,指针在开头,文件不存在则报错
a+ 追加模式,文件不存在则创建

常用的文件操作模式

5-2. 文件操作api

  • file.read([size])读取指定字节,如果未指定或为负数则读取所有
  • file.readlines([size])读取整行
  • file.write(str) 写入字符串,返回写入的字符长度
  • file.tell()返回文件当前位置
  • file.seek(offset[,whence])移动文件指针到指定位置
    • offset: 偏移量,如果为负数表示倒数
    • whence: 表示从哪个位置开始偏移,0代表从文件开头开始算,1代表从当前位置开始算,2代表从文件末尾开始算

二、网络请求

1. requests模块

1-1. requests.request(method, url, **kwargs)

# **kwargs: 当你传入key=value时存储的字典
# request方法的定义如下,
# 可以看出实际上是调用session.request方法.
def request(method, url, **kwargs):
	with sessions.Session() as session:
			return session.request(method=method, url=url, **kwargs)

1-2. sessions.Session().request请求参数介绍

  • mothod 请求方式,
  • url
  • params
  • data
  • json
  • headers
  • cookies
  • files
  • auth
  • timeout
  • allow_redirects
  • proxies
  • stream
  • verify
  • cert

1-3. requests.get(url, params, **kwargs)

# get方法定义
def get(url, params=None, **kwargs):
	kwargs.setdefault('allow_redirects', True)
    return request('get', url, params=params, **kwargs)

1-4. requests.post(url, data, json, **kwargs)

# post方法定义
def post(url, data=None, json=None, **kwargs):
    return request('post', url, data=data, json=json, **kwargs)

三、json模块

1. json.dumps(py_obj) 将py对象转换为json_str

2. json.loads(json_str) 将josn_str转换为py对象

3. json.dumps(py_obj,file) 将py对象转换成json_str写入file文件中

4. json.load(file) 将file文件中的数据转换为py对象

四、Mysql模块

1. import pymysql 导入pymysql包

2. db = pymysql.connect(...)连接数据库

db = pymysql.connect(host="localhost", user="root", password="root", database="test")

3. cursor = db.cursor() 游标

3-1. cursor.execute(sql_str) 执行sql,并将结果保存在cursor中

3-2. cursor.fetchone() 获取游标中的一个结果

3-3. cursor.fetchall() 获取所有结果

4. pymysql.converters.escape_string(str)字符串双引号单引号处理

5. 使用案例

import pymysql
db = pymysql.connect(host="localhost", user="root", password="root", database="test")
cursor = db.cursor()
select_sql_str = 'select id, name, age from person'
cursor.execute(select_sql_str)
row = cursor.fetchone()
id = row[0]
name = row[1]

insert_sql_str = "insert into person(name,age) values ('%s', %s)" % (name, age)
try:
	cursor.execute(insert_sql_str)
	db.commit()
except:
	db.rollback()
db.close()
原文地址:https://www.cnblogs.com/Serenity1994/p/14362708.html