0%

Python知识点记录

记录使用python遇到的一些工具和问题

学习Python之前,最好熟悉一下Python的语言和风格规范
https://google-styleguide.readthedocs.io/zh_CN/latest/google-python-styleguide/contents.html
原项目:https://github.com/google/styleguide
《PythonCookBook》:
https://python3-cookbook.readthedocs.io/zh_CN/latest/index.html

一些包和工具

虚拟环境(pipenv)

pip install pipenv

# 显式激活虚拟环境
pipenv shell

# 不显示激活虚拟环境而直接执行
pipenv run python hello.py

# 查看当前环境下的依赖情况
pipenv graph
pip list # 在虚拟环境中使用查看依赖列表。

# 生成requirements.txt文件
pip freeze >requirements.txt # 生成本地全部依赖,适用于虚拟环境

pip install pipreqs
pipreqs ./ --encoding=utf8 # 只生成该目录内的依赖

pipenv lock -r > requirements.txt

# 执行requirement.txt
pip install -r requirements.txt

# 安装 Pipfile.lock 中指定的所有包。
# (适用于测试环境等,因为使用 pipenv install 会更新 Pipfile.lock,可能导致版本不一致)
pipenv sync
  • 默认情况下,Pipenv会统一管理所有虚拟环境。在Windows系统中,虚拟环境文件夹会在C:\Users\Administrator\.virtualenvs\目录下创建,而Linux或macOS会在~/.local/share/virtualenvs/目录下创建。
  • 如果想在项目目录内创建虚拟环境文件夹.venv,有如下三种方法:
    • linux设置环境变量export PIPENV_VENV_IN_PROJECT=1
    • 自己在项目目录下手动创建.venv的目录,然后运行pipenv run或者pipenv shell pipenv都会在.venv下创建虚拟环境。
    • 设置WORKON_HOME到其他的地方 (如果当前目录下已经有.venv,此项设置失效)
  • 虚拟环境文件夹的目录名称的形式为“当前项目目录名+一串随机字符,比如helloflask-5Pa0ZfZw。

yield

在写查询元素的代码时,通常会使用包含 yield 表达式的生成器函数。这样可以将搜索过程代码和使用搜索结果代码解耦。

应用

批量有序重命名文件

import os,re
num = 1
path = 'C:\\Users\\Desktop\\test\\'
prefix = 'picture'
suffix = '.py'
for file in os.listdir(path):
fileregex = re.compile(r'\.\w*') #取得后缀名
extension = ''.join(fileregex.findall(file)[-1:]) #列表转换为字符串
if suffix:
newName = prefix+str(num)+suffix
else:
newName = prefix+str(num)+extension
if extension == '':
continue #过滤掉文件夹
os.rename(path+file, path+newName)
print(file+' to '+newName+' rename succeed!')
num = num+1