记录本人用到的一些命令

文中可替代量使用[具体参数]的形式代替

Anaconda环境管理

使用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

基础语法

  • 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
last_folder_name = os.path.basename([path])
  • 获取目录上一级目录
1
pre_folder = os.path.dirname([path])
  • .创建文本文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
with open([path], 'a',encoding='utf-8') as file:
# 写入数据
file.write(f"哈哈哈哈 \n")
"""
open()函数常见模式
'r':只读模式,如果文件不存在则抛出异常。
'w':写入模式,如果文件不存在则创建,如果文件已存在则覆盖原有内容。
'a':追加模式,如果文件不存在则创建,如果文件已存在则在末尾追加内容。
'x':独占写入模式,如果文件已存在则抛出异常。
'b':二进制模式,用于读取或写入二进制文件。
'U' 或 'rU':以读方式打开,同时提供通用换行符支持。
还可以通过组合这些模式来使用,如'r+'表示读写模式,'w+'表示写后读模式等。
"""

with open([path], 'r+',encoding='utf-8') as file:
file.truncate(0) # 清空文件内容
  • 读取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
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
"""
目的:整合多个实用方法,通过控制台进行方法快速调用并实现功能
"""
def case_a():
print("Case A")


def case_b():
print("Case B")


def case_c():
print("Case C")

# 拓展...


def switch_case(value):
switch_table = {
'1': case_a,
'2': case_b,
'3': case_c,
# 拓展...
}
return switch_table.get(value, lambda: print("!!!请输入有效操作!!!"))()


if __name__ == "__main__":

while True:
print("--------------------请输入操作--------------------")
print("1. add1")
print("2. add2")
print("3. add3")
# 拓展...
print("0. 退出")
print("------------------------------------------------")
key = input("请输入操作序号:")
if key == "0":
break
switch_case(key)

汉字转拼音

库:pip install pypinyin

Style.NORMAL:表示不带声调的拼音

Style.TONE:表示带有数字声调的拼音

Style.TONE2:表示带有声调数字的拼音

Style.TONE3:表示带有声调点的拼音

1
2
def chinese_to_pinyin(text, style=Style.NORMAL):
return ''.join([y[0] for y in pinyin(text, style=style)])

编译打包可执行文件

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

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

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