记录本人用到的一些命令

Python环境管理

使用Anaconda进行python环境管理,以下是常用指令

创建环境

1
conda create --name myenv

指定python版本

1
conda create --name myenv python=3.8

查看当前环境下的python版本

1
python --version

查看当前有的所有环境

1
conda env list

激活环境

1
conda activate myenv

退出环境

1
conda deactivate

删除环境

1
conda remove --name myenv --all

导出环境中所有包

1
conda list --name myenv > package-list.txt

使用包集合创建环境

1
conda create --name newenv --file package-list.txt

Python开发记录

基础语法

  • if...elif
1
2
3
4
5
6
7
# python中的if常见写法
if str == "file":
if [boolean] is False:
if not [boolean]:
if [boolean]:
if projection is not None:
if x < y < z:
  • for
1
2
3
4
5
6
7
8
9
10
11
# 遍历字符串中每个字符
for x in [string]:

# 从0开始循环到[number]结束的数字序列
for item in range([number]):

# 从[number1]开始循环到[number2]结束的数字序列
for item in range([number1],[number2]):

# 从[number1]开始,到[number2]结束(不含第二个[number2]本身),步长以step值为准
for item in range([number1],[number2],[step]):
  • try...except
1
2
3
4
5
6
try:
# ...
except OSError as e:
# ...
except RecursionError:
# ...

文件操作

  • 指定路径下的遍历操作
  1. 只对路径下的一级遍历
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import os

# 指定要遍历的目录路径
folder_path = r"[folder]" # 替换为你要遍历的文件夹路径

# 使用 os.listdir() 列出目录下的所有文件和子目录
for item in os.listdir(folder_path):
item_path = os.path.join(folder_path, item) # 构建完整的路径
if os.path.isfile(item_path):
print(f"当前路径指向是文件: {item_path}")
elif os.path.isdir(item_path):
print(f"当前路径指向是目录: {item_path}")
else:
print(f"其他: {item_path}")
  1. 整个文件夹下所有文件遍历
1
2
3
4
5
6
7
8
9
10
11
import os

# 指定要遍历的目录路径
folder_path = r"[folder]" # 替换为你要遍历的文件夹路径

for root, dirs, files in os.walk(folder_path):
print(f"当前目录: {root}")
print("子目录: ", dirs)
print("文件: ", files)
print("\n")

  • 判断目录是否存在,不存在则创建
1
2
if not os.path.exists([folder]):
os.makedirs(temp_path)
  • 获取文件名和后缀
1
2
3
4
# 返回文件名带后缀
os.path.basename([path])
# 返回[文件名字,后缀]列表
os.path.splitext(os.path.basename([path]))
  • 创建文本文件
1
2
3
4
5
6
7
8
9
10
11
12
13
with open([path], 'a') as file:
# 写入数据
file.write(f"哈哈哈哈 \n")
"""
open()函数常见模式
'r':只读模式,如果文件不存在则抛出异常。
'w':写入模式,如果文件不存在则创建,如果文件已存在则覆盖原有内容。
'a':追加模式,如果文件不存在则创建,如果文件已存在则在末尾追加内容。
'x':独占写入模式,如果文件已存在则抛出异常。
'b':二进制模式,用于读取或写入二进制文件。
'U' 或 'rU':以读方式打开,同时提供通用换行符支持。
还可以通过组合这些模式来使用,如'r+'表示读写模式,'w+'表示写后读模式等。
"""
  • 读取json文件
1
2
3
4
5
with open('arg.json', 'r') as file:
# json文件中的数据
json_data = json.load(file)
# 具体属性值
attr = json_data["attr"]
  • 删除文件/文件夹
  1. 删除文件
1
2
3
4
5
6
7
8
9
10
11
12
import os

# 指定要删除的文件路径
file_path = [path] # 替换为你要删除的文件路径

# 检查文件是否存在
if os.path.exists(file_path):
# 如果文件存在,使用 os.remove() 删除文件
os.remove(file_path)
print(f"{file_path} 文件已被删除")
else:
print(f"文件 {file_path} 不存在")
  1. 删除文件夹(当前的文件夹也会被删除)
1
2
3
4
5
6
7
8
9
import shutil

# 指定要删除的文件夹路径
folder_path = [folder] # 替换为你要删除的文件夹路径

# 使用 shutil.rmtree() 删除文件夹及其内容 (当前文件夹也会被删除)
shutil.rmtree(folder_path)
print(f"{folder_path} 文件夹及其内容已被删除")

常用方法

  • 清空某个文件夹
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import os
import shutil

def delete_files_and_folders(folder):
"""
清空文件夹
:param folder: 文件夹路径
:return:
"""
for root, dirs, files in os.walk(folder, topdown=False):
for name in files:
file_path = os.path.join(root, name)
os.remove(file_path)
print(f"文件 {file_path} 已被删除")
for name in dirs:
folder_path = os.path.join(root, name)
shutil.rmtree(folder_path)
print(f"文件夹 {folder_path} 及其内容已被删除")

delete_files_and_folders(target_folder)
  • 程序终止,控制台优化(打包后的场景)
1
2
3
4
5
6
7
8
9
10
11
def exit_app(msg="", code=1):
"""
退出程序
:param code: 0 代表正常退出,其它值代码异常退出
:param msg: 退出前的提示
:return:
"""
print()
print(msg)
input("按任意键退出...")
sys.exit(code)

编译打包可执行文件

打包成单个可执行文件:.exe

1
2
3
4
5
6
# 下载PyInstaller
pip install pyinstaller
# 进行打包操作
pyinstaller --onefile 需要打包的文件.py

# 会在根目录生成一个dist文件