0%

2_2_编程技巧

简介

  • python3 常用的编程技巧

python3 写入文件 追加模式

在 Python 3 中,可以使用 open() 函数以 追加模式 ('a''a+') 写入文件。以下是几种常见的方式:

1. 追加写入文本文件

1
2
with open("example.txt", "a", encoding="utf-8") as file:
file.write("这是追加的一行内容。\n")
  • 'a' 模式:如果文件不存在,会自动创建;如果文件存在,则从末尾追加内容。
  • encoding="utf-8":保证支持中文等字符,防止乱码。

2. 追加写入并读取文件

1
2
3
4
with open("example.txt", "a+", encoding="utf-8") as file:
file.write("追加的内容,带换行符。\n")
file.seek(0) # 将文件指针移到开头
print(file.read()) # 读取整个文件内容
  • 'a+' 模式:允许追加 (write) 和读取 (read)。
  • seek(0):让 read() 读取文件内容,否则它会从文件末尾开始,返回空字符串。

3. 追加二进制文件(如图片、视频)

1
2
with open("example.bin", "ab") as file:
file.write(b"\x00\x01\x02\x03") # 追加字节数据
  • 'ab' 模式:以二进制方式追加写入。

这样你就可以在 Python 3 中以追加模式写入文件了!

python3 pair类型

在 Python 3 中,没有专门的 pair 类型(像 C++ 中的 std::pair)。但是,你可以使用 元组 (tuple)列表 (list) 来表示一个 键值对成对数据


1. 使用元组 (tuple) 作为 pair

元组是 Python 中最常用的方式:

1
2
3
pair = (1, "apple")  # 一个整数和字符串的配对
print(pair[0]) # 输出 1
print(pair[1]) # 输出 "apple"

元组是 不可变的,适用于存储固定配对数据。


2. 使用列表 (list) 作为 pair

如果你需要修改 pair,可以使用列表:

1
2
3
pair = [1, "banana"]
pair[1] = "orange" # 修改第二个元素
print(pair) # 输出 [1, 'orange']

列表是 可变的,可以修改元素。


3. 使用字典 (dict) 处理键值对

如果要存储键值关系,dict 是更好的选择:

1
2
pair_dict = {"key": "value"}
print(pair_dict["key"]) # 输出 "value"

4. 使用 namedtuple(更具可读性)

如果你想让 pair 具有 结构化命名,可以使用 collections.namedtuple

1
2
3
4
5
6
7
from collections import namedtuple

Pair = namedtuple("Pair", ["first", "second"])
pair = Pair(1, "grape")

print(pair.first) # 输出 1
print(pair.second) # 输出 "grape"

这样比普通的 tuple 代码更清晰。


5. 使用 dataclass(更灵活的方式)

如果需要 更多功能,可以使用 dataclass

1
2
3
4
5
6
7
8
9
10
from dataclasses import dataclass

@dataclass
class Pair:
first: int
second: str

pair = Pair(1, "cherry")
print(pair.first) # 输出 1
print(pair.second) # 输出 "cherry"

dataclass 适用于需要进一步扩展的情况,比如方法或默认值。


结论:

方式 是否可变 适用场景
tuple ❌ 不可变 存储固定配对数据
list ✅ 可变 需要修改的配对
dict ✅ 可变 存储键值对
namedtuple ❌ 不可变 结构化、可读性好
dataclass ✅ 可变 需要扩展功能

如果你只是想存两个值,tuple 是最常用的方式。如果需要更高级的功能,可以用 namedtupledataclass

python3 字典按键排序

在 Python 3 中,可以使用 sorted() 函数按照 键(key) 对字典进行排序。以下是几种常见的方法:


1. 按键升序排序

1
2
3
4
data = {"banana": 3, "apple": 5, "cherry": 2}

sorted_dict = dict(sorted(data.items())) # 默认按键升序
print(sorted_dict)

输出:

1
{'apple': 5, 'banana': 3, 'cherry': 2}

sorted(data.items()) 默认按键升序排列


2. 按键降序排序

1
2
sorted_dict = dict(sorted(data.items(), reverse=True))
print(sorted_dict)

输出:

1
{'cherry': 2, 'banana': 3, 'apple': 5}

reverse=True 让键按降序排列


3. 自定义排序规则(忽略大小写)

如果键是字符串,并且想要 忽略大小写排序

1
2
3
4
data = {"Banana": 3, "apple": 5, "Cherry": 2}

sorted_dict = dict(sorted(data.items(), key=lambda x: x[0].lower()))
print(sorted_dict)

输出:

1
{'apple': 5, 'Banana': 3, 'Cherry': 2}

使用 key=lambda x: x[0].lower() 进行不区分大小写排序


4. 按键的长度排序

如果想要按 键的长度 排序:

1
2
sorted_dict = dict(sorted(data.items(), key=lambda x: len(x[0])))
print(sorted_dict)

使用 key=lambda x: len(x[0]) 按键的长度排序


5. 使用 collections.OrderedDict 保持顺序

如果你需要一个有序字典(Python 3.7+ 的 dict 默认保持顺序,但旧版本需要 OrderedDict):

1
2
3
4
from collections import OrderedDict

ordered_dict = OrderedDict(sorted(data.items()))
print(ordered_dict)

OrderedDict 在 Python 3.6 及以下版本中能保持顺序


🔥 总结:

方式 代码
按键升序排序 dict(sorted(data.items()))
按键降序排序 dict(sorted(data.items(), reverse=True))
忽略大小写排序 dict(sorted(data.items(), key=lambda x: x[0].lower()))
按键长度排序 dict(sorted(data.items(), key=lambda x: len(x[0])))
保持顺序的排序字典(旧版 Python) OrderedDict(sorted(data.items()))

推荐方式: dict(sorted(data.items())) 是最简洁、最快的排序方法! 🚀

python3 判断字符串中不包含指定子字符串

在 Python 3 中,判断一个字符串是否不包含指定的子字符串,可以通过几种不同的方式来实现:

1. 使用 not in 操作符

not in 是 Python 中最直观和常见的方式:

1
2
3
4
5
6
7
string = "Hello, world!"
substring = "python"

if substring not in string:
print("子字符串未找到")
else:
print("子字符串已找到")

输出:

1
子字符串未找到

not in 是判断子字符串不存在的简洁方法。


2. 使用 find() 方法

find() 方法返回子字符串第一次出现的位置,如果未找到则返回 -1

1
2
3
4
5
6
7
string = "Hello, world!"
substring = "python"

if string.find(substring) == -1:
print("子字符串未找到")
else:
print("子字符串已找到")

输出:

1
子字符串未找到

find() 也可以达到相同效果,不过它比较 -1 的结果,代码稍微冗长一些。


3. 使用 index() 方法

index() 方法与 find() 类似,但如果未找到子字符串会抛出异常 ValueError。一般不推荐直接用于检查是否包含,因为可能需要额外的错误处理。

1
2
3
4
5
6
7
8
string = "Hello, world!"
substring = "python"

try:
string.index(substring)
print("子字符串已找到")
except ValueError:
print("子字符串未找到")

输出:

1
子字符串未找到

4. 使用正则表达式

如果你需要更复杂的匹配条件,可以使用正则表达式模块 re

1
2
3
4
5
6
7
8
9
import re

string = "Hello, world!"
substring = "python"

if not re.search(substring, string):
print("子字符串未找到")
else:
print("子字符串已找到")

输出:

1
子字符串未找到

小结:

  • 最简单直观not in 操作符。
  • **find()index()**:适合判断具体的位置,但比 not in 稍微复杂。
  • 正则表达式:适合复杂匹配条件。

如果仅仅是判断是否不包含子字符串,**推荐使用 not in**,因为它简洁且易于理解。

python 调用edge打开指定网址

在 Python 中,可以使用 webbrowser 模块调用默认浏览器(如 Microsoft Edge)打开指定网址。如果需要明确指定 Edge,可以使用 Edge 的路径或通过命令行调用。以下是实现方法的示例:

方法一:通过 webbrowser 模块调用 Edge

1
2
3
4
5
6
7
8
9
10
import webbrowser

# 指定 Microsoft Edge 的路径(Windows 系统默认路径)
edge_path = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"

# 注册 Microsoft Edge
webbrowser.register('edge', None, webbrowser.BackgroundBrowser(edge_path))

# 使用 Edge 打开指定网址
webbrowser.get('edge').open('https://www.example.com')

方法二:通过 subprocess 模块调用 Edge

1
2
3
4
5
6
7
8
import subprocess

# Microsoft Edge 的路径(Windows 系统默认路径)
edge_path = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"

# 打开指定网址
url = "https://www.example.com"
subprocess.run([edge_path, url])

方法三:调用系统命令(适用于已将 Edge 设置为默认浏览器)

1
2
3
4
5
import os

# 打开指定网址
url = "https://www.example.com"
os.system(f"start microsoft-edge:{url}")

注意事项

  1. Edge 路径:确保 Edge 的路径正确。如果使用的是 64 位版本的 Edge,路径可能是 C:\Program Files\Microsoft\Edge\Application\msedge.exe
  2. 权限问题:运行程序时,需要有足够的权限调用系统路径或命令。
  3. Windows 专属:上述方法主要针对 Windows 系统。如果是其他操作系统,需根据实际环境调整。

python 根据指定分隔符分割字符串

在 Python 中,可以使用内置的 str.split() 方法根据指定分隔符分割字符串。以下是多种方式和示例:


基本用法:split()

split() 按照指定的分隔符将字符串分割成一个列表。

示例

1
2
3
4
5
# 使用逗号作为分隔符
text = "apple,banana,cherry"
result = text.split(",")

print(result) # 输出: ['apple', 'banana', 'cherry']

指定分隔符

默认情况下,split() 会以任意空白字符(如空格、制表符、换行符)作为分隔符。可以通过指定参数来自定义分隔符。

示例

1
2
3
4
5
# 按空格分割
text = "Hello World Python"
result = text.split(" ")

print(result) # 输出: ['Hello', 'World', 'Python']

限制分割次数

可以通过 maxsplit 参数限制分割的次数。maxsplit 表示最大分割次数,剩余部分作为最后一个元素返回。

示例

1
2
3
4
5
# 限制分割次数
text = "apple,banana,cherry,dates"
result = text.split(",", maxsplit=2)

print(result) # 输出: ['apple', 'banana', 'cherry,dates']

分割多种分隔符:使用 re.split()

如果字符串中存在多种分隔符,可以使用正则表达式模块 rere.split() 方法。

示例

1
2
3
4
5
6
7
import re

# 多种分隔符
text = "apple;banana|cherry,dates"
result = re.split(r"[;|,]", text)

print(result) # 输出: ['apple', 'banana', 'cherry', 'dates']

分割后去除空字符串

如果分割后的结果中可能存在空字符串,可以结合列表解析进行过滤。

示例

1
2
3
4
text = "apple,,banana,,cherry"
result = [item for item in text.split(",") if item]

print(result) # 输出: ['apple', 'banana', 'cherry']

按换行符分割

1
2
3
4
5
# 按换行符分割
text = "line1\nline2\nline3"
result = text.splitlines()

print(result) # 输出: ['line1', 'line2', 'line3']

常见场景

  1. 处理 CSV 数据

    1
    2
    3
    text = "name,age,city"
    data = text.split(",")
    print(data) # 输出: ['name', 'age', 'city']
  2. 解析日志

    1
    2
    3
    log = "INFO: 2025-01-11 12:34:56 - User logged in"
    result = log.split(" - ")
    print(result) # 输出: ['INFO: 2025-01-11 12:34:56', 'User logged in']
  3. 多分隔符解析

    1
    2
    3
    4
    5
    import re

    text = "apple;banana|cherry,dates"
    result = re.split(r"[;|,]", text)
    print(result) # 输出: ['apple', 'banana', 'cherry', 'dates']

总结

  • 单一分隔符:使用 str.split()
  • 多种分隔符:使用 re.split()
  • 限制分割次数:设置 maxsplit 参数。

如果需要对分割后的数据进一步处理或过滤,结合列表解析可以提高代码的简洁性和可读性。

python 读取文件数据直到结尾

在 Python 中,可以使用以下方法读取文件数据直到文件结尾:


方法 1:使用 read() 方法

read() 会读取整个文件内容,适合小文件。

1
2
3
4
5
6
# 读取整个文件内容
with open("example.txt", "r") as file:
data = file.read()

print("File content:")
print(data)

方法 2:使用 readline() 方法逐行读取

readline() 每次读取一行,直到文件结尾返回空字符串。

1
2
3
4
5
6
# 使用 readline() 逐行读取
with open("example.txt", "r") as file:
line = file.readline()
while line:
print(line.strip()) # strip() 去除换行符
line = file.readline()

方法 3:使用 readlines() 方法读取所有行

readlines() 将文件的所有行读入一个列表,适合需要处理每一行的场景。

1
2
3
4
5
6
# 读取所有行并逐行处理
with open("example.txt", "r") as file:
lines = file.readlines()

for line in lines:
print(line.strip()) # strip() 去除换行符

方法 4:使用文件对象迭代(推荐)

文件对象本身是可迭代的,每次迭代会返回一行内容。这是处理大文件的推荐方法。

1
2
3
4
# 迭代文件对象逐行读取
with open("example.txt", "r") as file:
for line in file:
print(line.strip())

方法对比

方法 适用场景 优点 缺点
read() 小文件,读取所有内容 简单易用,直接获取完整内容 大文件可能耗尽内存
readline() 按行处理内容,适合流式处理 控制读取过程,节约内存 需手动管理循环
readlines() 小文件,需要按行存储到列表中 获取完整的行列表,操作方便 大文件可能耗尽内存
文件对象迭代 逐行处理大文件(推荐) 高效,内存占用低 无法随机访问

文件末尾的标志

  • read()readline() 或文件迭代到文件末尾时,会返回空字符串 ''
  • 如果需要判断文件是否已经读取完毕,可以检查返回值是否为空。

错误处理

在读取文件时,可以使用 try...except 块捕获异常:

1
2
3
4
5
6
7
8
try:
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
except FileNotFoundError:
print("The file does not exist.")
except IOError as e:
print(f"An I/O error occurred: {e}")

总结

  • 使用 文件对象迭代 是处理大文件的推荐方式,结合 with 语句可以确保文件资源的自动释放。
  • 对于简单的读取需求,小文件可以直接使用 read()readlines()

如果有特定需求(如按行过滤数据或逐块读取大文件),可以进一步优化代码!

python 程序运行参数

在 Python 中,可以通过以下方式获取程序的运行参数:


方法 1:使用 sys.argv

sys.argv 是一个列表,包含从命令行传递给 Python 脚本的参数。

示例代码

1
2
3
4
5
6
7
8
import sys

# 输出所有命令行参数
print("Arguments:", sys.argv)

# 获取特定参数
if len(sys.argv) > 1:
print("First argument:", sys.argv[1])

运行脚本

1
python script.py arg1 arg2

输出

1
2
Arguments: ['script.py', 'arg1', 'arg2']
First argument: arg1

注意

  • sys.argv[0] 是脚本的文件名。
  • 参数以字符串形式存储。

方法 2:使用 argparse 模块

argparse 是一个标准库,用于定义和解析命令行参数,适合处理更复杂的参数。

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import argparse

# 创建解析器
parser = argparse.ArgumentParser(description="A sample script.")

# 添加参数
parser.add_argument("name", help="Your name") # 位置参数
parser.add_argument("-a", "--age", type=int, help="Your age") # 可选参数
parser.add_argument("-v", "--verbose", action="store_true", help="Increase output verbosity") # 开关参数

# 解析参数
args = parser.parse_args()

# 使用参数
print(f"Hello, {args.name}!")
if args.age:
print(f"You are {args.age} years old.")
if args.verbose:
print("Verbose mode is on.")

运行脚本

1
python script.py Alice -a 30 -v

输出

1
2
3
Hello, Alice!
You are 30 years old.
Verbose mode is on.

注意

  • add_argument 的参数可以自定义位置参数、类型和选项。
  • --help 会自动生成帮助信息。

方法 3:使用 optparse 模块

optparse 是一个早期的参数解析库,但已被 argparse 替代。一般不推荐新项目使用。

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from optparse import OptionParser

# 创建解析器
parser = OptionParser()

# 添加参数
parser.add_option("-n", "--name", dest="name", help="Your name")
parser.add_option("-a", "--age", dest="age", type="int", help="Your age")

# 解析参数
(options, args) = parser.parse_args()

# 使用参数
if options.name:
print(f"Hello, {options.name}!")
if options.age:
print(f"You are {options.age} years old.")

运行脚本

1
python script.py -n Alice -a 30

比较

特性 sys.argv argparse optparse
复杂参数解析 不支持 支持 支持
自动生成帮助信息 不支持 支持 支持
推荐度 简单脚本可用 推荐 不推荐(已弃用)

总结

  • 简单参数:使用 sys.argv
  • 复杂解析:使用 argparse,它功能强大且易于使用。
  • 已弃用工具:避免使用 optparse,尽量迁移到 argparse

如果需要详细示例或进一步自定义,请告诉我!

windows下python执行命令

在Windows下使用Python执行命令,可以通过以下几种方式:


1. 使用os.system

用于执行简单的系统命令,返回命令的退出状态码。

1
2
3
4
import os

# 执行命令
os.system("dir") # 在当前目录下列出文件

2. 使用subprocess模块

更强大且推荐使用的方法,可以捕获输出或处理更复杂的命令。

执行命令并直接查看输出

1
2
3
4
import subprocess

# 执行命令
subprocess.run("dir", shell=True)

获取命令输出

1
2
3
4
5
6
7
8
import subprocess

# 获取命令结果
result = subprocess.run("dir", shell=True, capture_output=True, text=True)

# 打印输出
print(result.stdout) # 标准输出
print(result.stderr) # 错误输出(如果有)

执行带参数的命令

1
2
3
4
import subprocess

# 通过列表方式传递参数(推荐)
subprocess.run(["ping", "127.0.0.1", "-n", "4"], shell=True)

3. **使用os.popen**(较旧,已不推荐)

可以捕获命令的输出,但功能有限。

1
2
3
4
5
import os

# 捕获命令输出
output = os.popen("dir").read()
print(output)

4. 使用shutil模块执行简单操作

如果只是执行文件操作(如复制、删除),可以使用shutil模块。

1
2
3
4
import shutil

# 复制文件
shutil.copy("source.txt", "destination.txt")

注意事项

  1. 使用shell=True时需谨慎

    • 会调用系统的命令解释器(如cmd),可能存在安全风险(如命令注入)。
    • 如果可以,尽量使用参数列表的方式传递命令。
  2. 管理员权限

    • 某些命令需要管理员权限,需以管理员身份运行Python程序。
  3. 路径问题

    • 如果涉及路径,使用Python的ospathlib模块生成正确的路径,避免路径分隔符问题(如反斜杠\)。

需要帮助具体实现某个命令吗?

python3 拷贝文件和目录

在 Python3 中,拷贝文件和目录可以使用内置的 shutil 模块,它提供了高效的方法来复制、移动和删除文件和目录。

以下是一些常用的 shutil 操作:

1. 拷贝文件

可以使用 shutil.copy() 来复制文件。此函数会将源文件复制到目标文件或目录,并保持文件的权限位不变。

1
2
3
4
5
6
7
import shutil

# 复制文件到指定目录
shutil.copy('source_file.txt', 'destination_directory/')

# 复制并重命名
shutil.copy('source_file.txt', 'destination_directory/new_name.txt')

2. 拷贝文件及其权限

使用 shutil.copy2() 复制文件时,它不仅复制文件内容,还会复制文件的元数据(例如文件修改时间)。

1
2
3
4
import shutil

# 复制文件及其权限和元数据
shutil.copy2('source_file.txt', 'destination_directory/')

3. 拷贝整个目录

要复制整个目录(包括其中的所有子目录和文件),可以使用 shutil.copytree()

1
2
3
4
import shutil

# 复制整个目录及其内容
shutil.copytree('source_directory', 'destination_directory')

注意:目标目录不能已经存在,否则会报错。如果需要覆盖现有目录,可以通过 shutil.rmtree() 删除后再进行拷贝。

4. 移动文件或目录

可以使用 shutil.move() 来移动文件或目录。

1
2
3
4
import shutil

# 移动文件或目录
shutil.move('source_path', 'destination_path')

5. 删除文件或目录

如果需要删除文件或目录,可以使用 shutil.rmtree() 删除整个目录树。

1
2
3
4
import shutil

# 删除整个目录及其所有内容
shutil.rmtree('directory_to_delete')

使用这些函数可以方便地进行文件和目录的复制、移动、重命名等操作。

python3 字符串转二进制

要将字符串转换为二进制数据,你可以使用 Python 的 encode() 方法。这个方法允许你将字符串编码为不同的字符集,并返回一个包含二进制数据的字节对象。默认情况下,它使用 UTF-8 编码。下面是一个示例:

1
2
3
4
5
6
7
8
# 字符串
text = "Hello World"

# 将字符串编码为二进制数据
binary_data = text.encode()

# 打印二进制数据
print(binary_data)

在这个示例中,encode() 方法将字符串 “Hello World” 编码为二进制数据。如果你想要使用特定的编码方式,你可以将编码名称作为 encode() 方法的参数传入,例如 text.encode('utf-16')

python3第三方库检测文件的编码是否正常

你可以使用第三方库 chardet 来检测文件的编码是否正常。这个库可以帮助你识别文件的编码类型,从而确定是否符合你的预期。以下是一个简单的示例代码,展示如何使用 chardet 来检测文件的编码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import chardet

def detect_encoding(file_path):
with open(file_path, 'rb') as f:
raw_data = f.read()
result = chardet.detect(raw_data)
encoding = result['encoding']
confidence = result['confidence']
return encoding, confidence

file_path = 'your_file_path_here'
encoding, confidence = detect_encoding(file_path)

if confidence > 0.5: # 设置一个自定义的置信度阈值
print(f"The encoding of the file is {encoding} with confidence {confidence}.")
else:
print("The encoding could not be reliably determined.")

在这个示例中,detect_encoding 函数接收文件路径作为参数,读取文件的二进制数据,并使用 chardet.detect 函数来获取文件的编码类型和置信度。最后,根据置信度决定是否可靠地确定了文件的编码类型。

python3 判断列表为空

在Python中,你可以使用以下方法来判断一个列表是否为空:

  1. 使用逻辑判断:

    1
    2
    3
    4
    5
    6
    my_list = []

    if not my_list:
    print("列表为空")
    else:
    print("列表不为空")
  2. 使用内置函数 len()

    1
    2
    3
    4
    5
    6
    my_list = []

    if len(my_list) == 0:
    print("列表为空")
    else:
    print("列表不为空")

两种方法都可以有效地判断列表是否为空。通常来说,第一种方法更加 Pythonic,因为它利用了 Python 中的隐式布尔转换,更加简洁和易读。

python3 将utf-16编码的文件更改为utf-8编码

你可以使用 Python 来将 UTF-16 编码的文件转换为 UTF-8 编码的文件。下面是一个简单的示例代码:

1
2
3
4
5
6
7
8
9
10
def convert_encoding(input_file, output_file, input_encoding='utf-16', output_encoding='utf-8'):
with open(input_file, 'r', encoding=input_encoding) as f:
content = f.read()
with open(output_file, 'w', encoding=output_encoding) as f:
f.write(content)

input_file = 'input_utf16.txt'
output_file = 'output_utf8.txt'

convert_encoding(input_file, output_file)

在这个示例中,我们定义了一个 convert_encoding 函数,它接收输入文件路径、输出文件路径以及输入和输出的编码类型作为参数。函数首先读取 UTF-16 编码的文件内容,然后将其写入到 UTF-8 编码的输出文件中。你可以根据实际情况调整文件路径和编码类型。

python3 输出变量的类型

在Python中,您可以使用type()函数来输出变量的类型。以下是一个简单的示例:

1
2
3
4
5
6
7
8
x = 10
print(type(x)) # 输出: <class 'int'>

y = 'hello'
print(type(y)) # 输出: <class 'str'>

z = [1, 2, 3]
print(type(z)) # 输出: <class 'list'>

在这个示例中,我们定义了三个变量xyz,并使用type()函数输出它们的类型。对于整数x,输出的类型是int;对于字符串y,输出的类型是str;对于列表z,输出的类型是list

感谢老板支持!敬礼(^^ゞ