<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Python 教程归档 - 帝讯博客</title>
	<atom:link href="https://www.dixunblog.cn/tag/python-%E6%95%99%E7%A8%8B/feed" rel="self" type="application/rss+xml" />
	<link>https://www.dixunblog.cn/tag/python-教程</link>
	<description>致力于打造专业的互联网资讯平台</description>
	<lastBuildDate>Mon, 06 Apr 2026 00:30:07 +0000</lastBuildDate>
	<language>zh-Hans</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0</generator>

<image>
	<url>https://cdn.hyclive.cn/dixunblog/2025/12/cropped-ico-32x32.png</url>
	<title>Python 教程归档 - 帝讯博客</title>
	<link>https://www.dixunblog.cn/tag/python-教程</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Python 条件判断与循环语句 &#8211; 实战篇</title>
		<link>https://www.dixunblog.cn/1568.html</link>
					<comments>https://www.dixunblog.cn/1568.html#respond</comments>
		
		<dc:creator><![CDATA[小编]]></dc:creator>
		<pubDate>Mon, 06 Apr 2026 00:30:07 +0000</pubDate>
				<category><![CDATA[技术教程]]></category>
		<category><![CDATA[Python 教程]]></category>
		<category><![CDATA[python-flow]]></category>
		<category><![CDATA[代码教程]]></category>
		<guid isPermaLink="false">https://www.dixunblog.cn/1568.html</guid>

					<description><![CDATA[<p>欢迎来到今天的 Python 基础教程！今天我们来深入讲解 Python 条件判断与循环语句。</p>
<p>一、条件判断</p>
<p>1.1 if 语句<br />
<code class="language-python">age = 18</p>
<p>if age &#62;= 18:<br />
    print("成年人")<br />
else:<br />
    print("未成年人"...</p>
<p><a href="https://www.dixunblog.cn/1568.html">Python 条件判断与循环语句 &#8211; 实战篇</a>最先出现在<a href="https://www.dixunblog.cn">帝讯博客</a>。</p>
]]></description>
										<content:encoded><![CDATA[<p>欢迎来到今天的 Python 基础教程！今天我们来深入讲解 Python 条件判断与循环语句。</p>
<h2>一、条件判断</h2>
<h3>1.1 if 语句</h3>
<pre><code class="language-python">age = 18

if age &gt;= 18:
    print("成年人")
else:
    print("未成年人")</code></pre>
<h3>1.2 elif 多条件</h3>
<pre><code class="language-python">score = 85

if score &gt;= 90:
    print("优秀")
elif score &gt;= 80:
    print("良好")
elif score &gt;= 60:
    print("及格")
else:
    print("不及格")</code></pre>
<h2>二、循环语句</h2>
<h3>2.1 for 循环</h3>
<pre><code class="language-python"># 遍历列表
fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:
    print(fruit)

# 范围循环
for i in range(5):
    print(i)  # 0 到 4</code></pre>
<h3>2.2 while 循环</h3>
<pre><code class="language-python">count = 0
while count &lt; 5:
    print(count)
    count += 1</code></pre>
<h2>三、循环控制</h2>
<pre><code class="language-python"># break - 跳出循环
for i in range(10):
    if i == 5:
        break
    print(i)  # 0-4

# continue - 跳过本次
for i in range(5):
    if i == 3:
        continue
    print(i)  # 0,1,2,4</code></pre>
<h2>四、实战示例</h2>
<pre><code class="language-python"># 猜数字游戏
import random

number = random.randint(1, 100)
guess = 0

while guess != number:
    guess = int(input("猜一个 1-100 的数字："))
    if guess &gt; number:
        print("太大了")
    elif guess &lt; number:
        print(&quot;太小了&quot;)
    else:
        print(&quot;猜对了！&quot;)</code></pre>
<h2>五、总结</h2>
<p>条件判断和循环是编程的基础。建议多练习。</p>
<hr>
<p><em>关注我们获取更多 Python 教程！</em></p>
<p><a href="https://www.dixunblog.cn/1568.html">Python 条件判断与循环语句 &#8211; 实战篇</a>最先出现在<a href="https://www.dixunblog.cn">帝讯博客</a>。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.dixunblog.cn/1568.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Python 运算符与表达式详解 &#8211; 进阶篇</title>
		<link>https://www.dixunblog.cn/1567.html</link>
					<comments>https://www.dixunblog.cn/1567.html#respond</comments>
		
		<dc:creator><![CDATA[小编]]></dc:creator>
		<pubDate>Mon, 06 Apr 2026 00:30:05 +0000</pubDate>
				<category><![CDATA[技术教程]]></category>
		<category><![CDATA[Python 教程]]></category>
		<category><![CDATA[python-operator]]></category>
		<category><![CDATA[代码教程]]></category>
		<guid isPermaLink="false">https://www.dixunblog.cn/1567.html</guid>

					<description><![CDATA[<p>欢迎来到今天的 Python 基础教程！今天我们来深入讲解 Python 运算符与表达式。</p>
<p>一、算术运算符</p>
<p>1.1 基本运算<br />
<code class="language-python">a = 10<br />
b = 3</p>
<p>print(a + b)  # 加法：13<br />
print(a - b)  # 减法：7<br />
print(a ...</p>
<p><a href="https://www.dixunblog.cn/1567.html">Python 运算符与表达式详解 &#8211; 进阶篇</a>最先出现在<a href="https://www.dixunblog.cn">帝讯博客</a>。</p>
]]></description>
										<content:encoded><![CDATA[<p>欢迎来到今天的 Python 基础教程！今天我们来深入讲解 Python 运算符与表达式。</p>
<h2>一、算术运算符</h2>
<h3>1.1 基本运算</h3>
<pre><code class="language-python">a = 10
b = 3

print(a + b)  # 加法：13
print(a - b)  # 减法：7
print(a * b)  # 乘法：30
print(a / b)  # 除法：3.333...
print(a // b) # 整除：3
print(a % b)  # 取余：1
print(a ** b) # 幂运算：1000</code></pre>
<h3>1.2 应用场景</h3>
<pre><code class="language-python"># 计算折扣
price = 100
discount = 0.8
final_price = price * discount

# 判断奇偶
num = 17
if num % 2 == 0:
    print("偶数")
else:
    print("奇数")</code></pre>
<h2>二、比较运算符</h2>
<pre><code class="language-python">x = 5
y = 10

print(x == y)  # 等于：False
print(x != y)  # 不等于：True
print(x &gt; y)   # 大于：False
print(x = 5)  # 大于等于：True
print(y &lt;= 10) # 小于等于：True</code></pre>
<h2>三、逻辑运算符</h2>
<pre><code class="language-python">a = True
b = False

print(a and b)  # 与：False
print(a or b)   # 或：True
print(not a)    # 非：False

# 短路求值
result = False and print("不会执行")
result = True or print("不会执行")</code></pre>
<h2>四、位运算符</h2>
<pre><code class="language-python">a = 60    # 0011 1100
b = 13    # 0000 1101

print(a &amp; b)   # 与：12  (0000 1100)
print(a | b)   # 或：61  (0011 1101)
print(a ^ b)   # 异或：49 (0011 0001)
print(~a)      # 取反：-61
print(a &lt;&gt; 2)  # 右移：15</code></pre>
<h2>五、赋值运算符</h2>
<pre><code class="language-python">x = 10
x += 5   # x = x + 5
x -= 3   # x = x - 3
x *= 2   # x = x * 2
x /= 4   # x = x / 4
x //= 2  # x = x // 2
x %= 3   # x = x % 3
x **= 2  # x = x ** 2</code></pre>
<h2>六、成员运算符</h2>
<pre><code class="language-python">fruits = ["苹果", "香蕉", "橙子"]

print("苹果" in fruits)      # True
print("葡萄" not in fruits)  # True

text = "Hello, Python!"
print("Python" in text)      # True</code></pre>
<h2>七、身份运算符</h2>
<pre><code class="language-python">a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b)    # True（值相等）
print(a is b)    # False（不是同一对象）
print(a is c)    # True（同一对象）
print(a is not b) # True</code></pre>
<h2>八、运算符优先级</h2>
<pre><code class="language-python"># 优先级从高到低
# 1. 括号 ()
# 2. 幂 **
# 3. 正负 +x, -x
# 4. 算术 *, /, //, %
# 5. 算术 +, -
# 6. 比较 ==, !=, &gt;, &lt;
# 7. 逻辑 not, and, or

result = 2 + 3 * 4  # 14。不是 20
result = (2 + 3) * 4  # 20</code></pre>
<h2>九、实战示例</h2>
<pre><code class="language-python"># 计算三角形面积（海伦公式）
import math

a, b, c = 3, 4, 5
s = (a + b + c) / 2
area = math.sqrt(s * (s-a) * (s-b) * (s-c))
print(f"面积：{area}")

# 判断闰年
year = 2024
is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
print(f"{year}是闰年：{is_leap}")</code></pre>
<h2>十、总结</h2>
<p>掌握运算符是 Python 编程的基础。建议多练习。</p>
<hr>
<p><em>关注我们获取更多 Python 教程！</em></p>
<p><a href="https://www.dixunblog.cn/1567.html">Python 运算符与表达式详解 &#8211; 进阶篇</a>最先出现在<a href="https://www.dixunblog.cn">帝讯博客</a>。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.dixunblog.cn/1567.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Python 变量与数据类型完全指南 &#8211; 基础篇</title>
		<link>https://www.dixunblog.cn/1566.html</link>
					<comments>https://www.dixunblog.cn/1566.html#respond</comments>
		
		<dc:creator><![CDATA[小编]]></dc:creator>
		<pubDate>Mon, 06 Apr 2026 00:30:03 +0000</pubDate>
				<category><![CDATA[技术教程]]></category>
		<category><![CDATA[Python 教程]]></category>
		<category><![CDATA[python-basic]]></category>
		<category><![CDATA[代码教程]]></category>
		<guid isPermaLink="false">https://www.dixunblog.cn/1566.html</guid>

					<description><![CDATA[<p>欢迎来到今天的 Python 基础教程！今天我们来深入讲解 Python 变量与数据类型。这是 Python 编程的基石，掌握它们对后续学习至关重要。</p>
<p>一、Python 变量基础</p>
<p>1.1 变量的定义<br />
Python 变量不需要声明类型。直接赋值即可。Python 是动态类型语言。变量的类型在运行时确定：<br />
&#60;code ...</p>
<p><a href="https://www.dixunblog.cn/1566.html">Python 变量与数据类型完全指南 &#8211; 基础篇</a>最先出现在<a href="https://www.dixunblog.cn">帝讯博客</a>。</p>
]]></description>
										<content:encoded><![CDATA[<p>欢迎来到今天的 Python 基础教程！今天我们来深入讲解 Python 变量与数据类型。这是 Python 编程的基石，掌握它们对后续学习至关重要。</p>
<h2>一、Python 变量基础</h2>
<h3>1.1 变量的定义</h3>
<p>Python 变量不需要声明类型。直接赋值即可。Python 是动态类型语言。变量的类型在运行时确定：</p>
<pre><code class="language-python"># 变量定义 - 无需声明类型
name = "Python"        # 字符串
version = 3.12         # 浮点数
is_awesome = True      # 布尔值
count = 100            # 整数

# 查看变量类型
print(type(name))      # &lt;class 'str'&gt;
print(type(version))   # &lt;class 'float'&gt;
print(type(count))     # &lt;class 'int'&gt;

# 变量可以重新赋值为不同类型
count = "一百"         # 现在变成字符串了
print(type(count))     # &lt;class 'str'&gt;</code></pre>
<h3>1.2 命名规则</h3>
<p>遵循良好的命名规范可以让代码更易读：</p>
<ul>
<li><strong>基本规则</strong>：只能包含字母、数字、下划线</li>
<li><strong>不能以数字开头</strong>：如 1name 是非法的</li>
<li><strong>区分大小写</strong>：Name 和 name 是不同的变量</li>
<li><strong>不能使用 Python 关键字</strong>：如 if、for、while 等</li>
<li><strong>推荐使用小写字母和下划线</strong>：如 user_name、total_count</li>
</ul>
<pre><code class="language-python"># 合法的变量名
user_name = "张三"
age = 25
_total = 100

# 非法的变量名（会报错）
# 1name = "李四"      # 不能以数字开头
# class = "Python"    # 不能使用关键字
# my-name = "王五"    # 不能包含连字符

# 查看 Python 关键字
import keyword
print(keyword.kwlist)  # 打印所有关键字</code></pre>
<h2>二、基本数据类型</h2>
<h3>2.1 数值类型</h3>
<p>Python 支持多种数值类型。包括整数、浮点数和复数：</p>
<pre><code class="language-python"># 整数（int）- 任意精度
age = 25
population = 1400000000  # 14 亿
big_num = 10 ** 100      # 1 后面 100 个零。Python 能处理

# 浮点数（float）- 带小数点
price = 99.99
pi = 3.141592653589793
scientific = 1.23e-4     # 科学计数法。等于 0.000123

# 复数（complex）- 用于科学计算
complex_num = 3 + 4j
print(complex_num.real)  # 3.0（实部）
print(complex_num.imag)  # 4.0（虚部）

# 数值运算
a = 10
b = 3
print(a + b)   # 13（加法）
print(a - b)   # 7（减法）
print(a * b)   # 30（乘法）
print(a / b)   # 3.333...（除法。结果总是浮点数）
print(a // b)  # 3（整除。只取整数部分）
print(a % b)   # 1（取余）
print(a ** b)  # 1000（幂运算。10 的 3 次方）</code></pre>
<h3>2.2 字符串类型</h3>
<p>字符串是 Python 中最常用的数据类型之一：</p>
<pre><code class="language-python"># 字符串定义 - 可以用单引号或双引号
text1 = 'Hello'
text2 = "World"

# 多行字符串（使用三引号）
multiline = '''第一行
第二行
第三行'''

# 字符串拼接
greeting = "Hello" + " " + "Python"
print(greeting)  # Hello Python

# 字符串重复
line = "-" * 50
print(line)  # --------------------------------------------------

# 字符串索引和切片
text = "Python"
print(text[0])    # 'P'（第一个字符）
print(text[-1])   # 'n'（最后一个字符）
print(text[0:3])  # 'Pyt'（切片。不包含结束位置）
print(text[:3])   # 'Pyt'（省略开始位置）
print(text[3:])   # 'hon'（省略结束位置）

# 常用字符串方法
name = "  Python  "
print(name.strip())      # 'Python'（去除两端空格）
print(name.upper())      # '  PYTHON  '（转大写）
print(name.lower())      # '  python  '（转小写）
print(len(name))         # 10（字符串长度）

# 字符串格式化
name = "张三"
age = 25
# f-string（Python 3.6+ 推荐）
print(f"我叫{name}。今年{age}岁")
# format 方法
print("我叫{}。今年{}岁".format(name, age))</code></pre>
<h3>2.3 布尔类型</h3>
<pre><code class="language-python"># 布尔值 - 只有 True 和 False
is_valid = True
is_error = False

# 布尔运算
print(True and False)   # False（与）
print(True or False)    # True（或）
print(not True)         # False（非）

# 比较运算返回布尔值
print(5 &gt; 3)    # True
print(5 == 5)   # True
print(5 != 3)   # True

# 真值测试 - 以下值为 False
print(bool(0))        # False
print(bool(""))       # False
print(bool(None))     # False
print(bool([]))       # False
print(bool({}))       # False

# 其他值都为 True
print(bool(1))        # True
print(bool("a"))      # True
print(bool([1]))      # True</code></pre>
<h2>三、容器数据类型</h2>
<h3>3.1 列表（List）</h3>
<p>列表是最常用的容器类型。可以存储有序的元素集合：</p>
<pre><code class="language-python"># 列表定义
fruits = ["苹果", "香蕉", "橙子"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]  # 可以包含不同类型

# 访问元素
print(fruits[0])    # '苹果'
print(fruits[-1])   # '橙子'（最后一个）

# 修改元素
fruits[1] = "葡萄"
print(fruits)  # ['苹果', '葡萄', '橙子']

# 添加元素
fruits.append("西瓜")      # 末尾添加
fruits.insert(1, "香蕉")   # 指定位置插入
fruits.extend(["梨", "桃"])  # 扩展列表

# 删除元素
fruits.remove("苹果")      # 删除指定值
del fruits[0]              # 删除指定位置
last = fruits.pop()        # 弹出最后一个元素

# 列表切片
numbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:4])   # [1, 2, 3]
print(numbers[:3])    # [0, 1, 2]
print(numbers[::2])   # [0, 2, 4]（步长为 2）

# 列表推导式（强大功能）
squares = [x**2 for x in range(10)]
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# 常用列表方法
nums = [3, 1, 4, 1, 5, 9, 2, 6]
print(len(nums))     # 8（长度）
print(max(nums))     # 9（最大值）
print(min(nums))     # 1（最小值）
print(sum(nums))     # 31（求和）
nums.sort()          # 排序
print(nums)          # [1, 1, 2, 3, 4, 5, 6, 9]
print(nums.count(1)) # 2（计数）</code></pre>
<h3>3.2 元组（Tuple）</h3>
<p>元组是不可变的列表。适合存储不应改变的数据：</p>
<pre><code class="language-python"># 元组定义
coordinates = (10, 20)
colors = ("red", "green", "blue")
single = (42,)  # 单元素元组需要逗号

# 访问元素（和列表一样）
print(coordinates[0])  # 10
print(colors[-1])      # 'blue'

# 元组解包
x, y = coordinates
print(x, y)  # 10 20

# 交换变量值
a, b = 1, 2
a, b = b, a
print(a, b)  # 2 1

# 元组不可变（尝试修改会报错）
# coordinates[0] = 100  # TypeError!

# 元组的应用场景
# 1. 函数返回多个值
def get_user():
    return ("张三", 25, "北京")

name, age, city = get_user()

# 2. 字典的键（元组可哈希）
location = {(39.9, 116.4): "北京"}

# 3. 保护数据不被修改
RGB_RED = (255, 0, 0)</code></pre>
<h3>3.3 字典（Dictionary）</h3>
<p>字典是键值对的集合。用于存储映射关系：</p>
<pre><code class="language-python"># 字典定义
person = {
    "name": "张三",
    "age": 25,
    "city": "北京",
    "skills": ["Python", "Java", "Linux"]
}

# 访问值
print(person["name"])        # '张三'
print(person.get("age"))     # 25
print(person.get("email"))   # None（键不存在不报错）
print(person.get("email", "未提供"))  # '未提供'（默认值）

# 添加/修改键值对
person["email"] = "zhangsan@example.com"  # 添加
person["age"] = 26  # 修改

# 删除键值对
del person["city"]
age = person.pop("age")  # 弹出并返回值

# 遍历字典
for key, value in person.items():
    print(f"{key}: {value}")

# 常用操作
print("name" in person)      # True（检查键是否存在）
print(person.keys())         # 所有键
print(person.values())       # 所有值
print(len(person))           # 字典大小

# 字典推导式
squares = {x: x**2 for x in range(5)}
print(squares)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# 实际应用 - 统计词频
text = "python is great python is fun"
words = text.split()
freq = {}
for word in words:
    freq[word] = freq.get(word, 0) + 1
print(freq)  # {'python': 2, 'is': 2, 'great': 1, 'fun': 1}</code></pre>
<h3>3.4 集合（Set）</h3>
<p>集合是无序且不重复的元素集合：</p>
<pre><code class="language-python"># 集合定义
unique_nums = {1, 2, 3, 3, 4}
print(unique_nums)  # {1, 2, 3, 4}（自动去重）

# 创建空集合（注意：{}是空字典）
empty_set = set()

# 从列表创建集合（去重）
nums = [1, 2, 2, 3, 3, 3]
unique = set(nums)
print(unique)  # {1, 2, 3}

# 集合运算
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)  # {1, 2, 3, 4, 5, 6}（并集）
print(a &amp; b)  # {3, 4}（交集）
print(a - b)  # {1, 2}（差集）
print(a ^ b)  # {1, 2, 5, 6}（对称差集）

# 集合方法
a.add(5)           # 添加元素
a.remove(1)        # 删除元素（不存在会报错）
a.discard(10)      # 删除元素（不存在不报错）
print(3 in a)      # True（成员检查）</code></pre>
<h2>四、类型转换</h2>
<pre><code class="language-python"># 显式类型转换
num_str = "123"
num_int = int(num_str)      # 字符串转整数：123
num_float = float("3.14")   # 字符串转浮点：3.14
num_str = str(456)          # 整数转字符串："456"

# 列表、元组、集合互转
my_list = [1, 2, 3]
my_tuple = tuple(my_list)   # 列表转元组
my_set = set(my_list)       # 列表转集合

# 实际应用
# 1. 用户输入处理
age_str = input("请输入年龄：")
age = int(age_str)  # 转整数进行计算

# 2. 数据去重
ids = [1, 2, 2, 3, 3, 3]
unique_ids = list(set(ids))  # [1, 2, 3]

# 3. 数字格式化
price = 99.99
print(f"价格：{int(price)}元")  # 价格：99 元</code></pre>
<h2>五、实战示例</h2>
<h3>5.1 学生信息管理系统</h3>
<pre><code class="language-python"># 使用字典和列表管理学生信息
students = [
    {"name": "张三", "age": 20, "score": 85},
    {"name": "李四", "age": 21, "score": 92},
    {"name": "王五", "age": 19, "score": 78}
]

# 添加学生
new_student = {"name": "赵六", "age": 20, "score": 88}
students.append(new_student)

# 计算平均分
total = sum(s["score"] for s in students)
average = total / len(students)
print(f"平均分：{average:.2f}")

# 找出最高分
best_student = max(students, key=lambda s: s["score"])
print(f"最高分：{best_student['name']} - {best_student['score']}")

# 筛选及格学生
passed = [s for s in students if s["score"] &gt;= 60]
print(f"及格人数：{len(passed)}")</code></pre>
<h3>5.2 购物车程序</h3>
<pre><code class="language-python"># 购物车数据结构
cart = {
    "items": [
        {"name": "iPhone 15", "price": 7999, "quantity": 1},
        {"name": "AirPods", "price": 1299, "quantity": 2}
    ],
    "discount": 0.9  # 9 折优惠
}

# 计算总价
total = 0
for item in cart["items"]:
    item_total = item["price"] * item["quantity"]
    total += item_total

# 应用折扣
final_price = total * cart["discount"]
print(f"原价：{total}元")
print(f"折后价：{final_price:.2f}元")

# 添加商品
cart["items"].append({"name": "充电器", "price": 149, "quantity": 1})</code></pre>
<h2>六、常见错误与解决</h2>
<h3>6.1 类型错误</h3>
<pre><code class="language-python"># 错误：字符串和整数不能直接相加
# result = "年龄：" + 25  # TypeError

# 正确做法
result = "年龄：" + str(25)
result = f"年龄：{25}"  # 推荐</code></pre>
<h3>6.2 索引越界</h3>
<pre><code class="language-python">fruits = ["苹果", "香蕉", "橙子"]
# print(fruits[5])  # IndexError!

# 安全访问
if len(fruits) &gt; 5:
    print(fruits[5])
    
# 或使用切片（不会报错）
print(fruits[5:6])  # []</code></pre>
<h3>6.3 键不存在</h3>
<pre><code class="language-python">person = {"name": "张三"}
# print(person["age"])  # KeyError!

# 安全访问
print(person.get("age"))  # None
print(person.get("age", 0))  # 0（默认值）</code></pre>
<h2>七、最佳实践</h2>
<ol>
<li><strong>使用有意义的变量名</strong>：user_name 比 un 更好</li>
<li><strong>遵循命名规范</strong>：变量用小写 + 下划线</li>
<li><strong>选择合适的数据类型</strong>：不变数据用元组。需要去重用集合</li>
<li><strong>使用类型提示</strong>（Python 3.5+）：
<pre><code class="language-python">def greet(name: str) -&gt; str:
    return f"Hello, {name}"</code></pre>
</li>
<li><strong>善用列表推导式</strong>：简洁但不要太复杂</li>
</ol>
<h2>八、总结与练习</h2>
<p>今天我们学习了 Python 变量和数据类型的核心知识。建议：</p>
<ol>
<li><strong>理解不同数据类型的特点</strong>：何时用列表、元组、字典、集合</li>
<li><strong>掌握容器的使用方法</strong>：增删改查、遍历、推导式</li>
<li><strong>熟练进行类型转换</strong>：int()、str()、float()、list() 等</li>
<li><strong>多写代码巩固知识</strong>：实践是最好的老师</li>
</ol>
<h3>课后练习</h3>
<ol>
<li>创建一个包含 5 个学生信息的列表。每个学生有姓名、年龄、成绩</li>
<li>计算平均分、最高分、最低分</li>
<li>筛选出成绩大于 80 的学生</li>
<li>将学生按成绩排序</li>
</ol>
<hr>
<p><em>关注我们获取更多 Python 教程！下节课我们将学习 Python 运算符与表达式。</em></p>
<p><a href="https://www.dixunblog.cn/1566.html">Python 变量与数据类型完全指南 &#8211; 基础篇</a>最先出现在<a href="https://www.dixunblog.cn">帝讯博客</a>。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.dixunblog.cn/1566.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Python 网络爬虫入门实战 &#8211; 实战篇</title>
		<link>https://www.dixunblog.cn/1455.html</link>
					<comments>https://www.dixunblog.cn/1455.html#respond</comments>
		
		<dc:creator><![CDATA[小编]]></dc:creator>
		<pubDate>Mon, 30 Mar 2026 02:05:58 +0000</pubDate>
				<category><![CDATA[技术教程]]></category>
		<category><![CDATA[编程代码]]></category>
		<category><![CDATA[Python 教程]]></category>
		<category><![CDATA[python-crawler]]></category>
		<category><![CDATA[代码教程]]></category>
		<guid isPermaLink="false">https://www.dixunblog.cn/1455.html</guid>

					<description><![CDATA[<p>欢迎来到今天的 Python 实战教程！今天我们来学习 Python 网络爬虫入门实战。</p>
<p>一、环境准备</p>
<p><code class="language-bash">pip install requests beautifulsoup4 lxml</p>
<p>二、基础请求</p>
<p>&#60;code class=&#34;language-python...</p>
<p><a href="https://www.dixunblog.cn/1455.html">Python 网络爬虫入门实战 &#8211; 实战篇</a>最先出现在<a href="https://www.dixunblog.cn">帝讯博客</a>。</p>
]]></description>
										<content:encoded><![CDATA[<p>欢迎来到今天的 Python 实战教程！今天我们来学习 Python 网络爬虫入门实战。</p>
<h2><img fetchpriority="high" decoding="async" class="alignnone size-full wp-image-1457" src="http://cdn.hyclive.cn/dixunblog/2026/03/生成-Python-爬虫入门实战图片.png" alt="" width="2730" height="1535" /></h2>
<h2>一、环境准备</h2>
<pre><code class="language-bash">pip install requests beautifulsoup4 lxml</code></pre>
<h2>二、基础请求</h2>
<pre><code class="language-python">import requests

# GET 请求
response = requests.get('https://www.example.com')
print(response.status_code)
print(response.text)</code></pre>
<h2>三、解析 HTML</h2>
<pre><code class="language-python">from bs4 import BeautifulSoup

html = '''</code></pre>
<h1>标题</h1>
<pre><code class="language-python"></code></pre>
<p>&#8221;&#8217; soup = BeautifulSoup(html, &#8216;lxml&#8217;) print(soup.h1.text)</p>
<pre><code class="language-python"></code></pre>
<h2>四、实战示例</h2>
<pre><code class="language-python"># 爬取新闻标题
import requests
from bs4 import BeautifulSoup

url = 'https://news.example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'lxml')

headlines = soup.find_all('h2', class_='headline')
for h in headlines:
    print(h.text)</code></pre>
<h2>五、注意事项</h2>
<ol>
<li>遵守 robots.txt 协议</li>
<li>控制请求频率</li>
<li>使用 User-Agent</li>
<li>合法合规使用数据</li>
</ol>
<h2>六、总结</h2>
<p>网络爬虫是 Python 实战的重要应用。建议多实践。</p>
<hr />
<p><em>关注我们获取更多 Python 实战教程！</em></p>
<p><a href="https://www.dixunblog.cn/1455.html">Python 网络爬虫入门实战 &#8211; 实战篇</a>最先出现在<a href="https://www.dixunblog.cn">帝讯博客</a>。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.dixunblog.cn/1455.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Python 文件批量处理与自动化 &#8211; 进阶篇</title>
		<link>https://www.dixunblog.cn/1454.html</link>
					<comments>https://www.dixunblog.cn/1454.html#respond</comments>
		
		<dc:creator><![CDATA[小编]]></dc:creator>
		<pubDate>Mon, 30 Mar 2026 02:05:57 +0000</pubDate>
				<category><![CDATA[技术教程]]></category>
		<category><![CDATA[编程代码]]></category>
		<category><![CDATA[Python 教程]]></category>
		<category><![CDATA[python-file]]></category>
		<category><![CDATA[代码教程]]></category>
		<guid isPermaLink="false">https://www.dixunblog.cn/1454.html</guid>

					<description><![CDATA[<p>欢迎来到今天的 Python 实战教程！今天我们来深入学习 Python 文件批量处理与自动化。这是每个 Python 开发者都必须掌握的核心技能。无论是处理日志文件、批量重命名、数据清洗。还是自动化办公。都离不开文件操作。</p>
<p>一、文件读写基础</p>
<p>1.1 打开文件的正确方式<br />
Python 使用 open() 函数打开文...</p>
<p><a href="https://www.dixunblog.cn/1454.html">Python 文件批量处理与自动化 &#8211; 进阶篇</a>最先出现在<a href="https://www.dixunblog.cn">帝讯博客</a>。</p>
]]></description>
										<content:encoded><![CDATA[<p>欢迎来到今天的 Python 实战教程！今天我们来深入学习 Python 文件批量处理与自动化。这是每个 Python 开发者都必须掌握的核心技能。无论是处理日志文件、批量重命名、数据清洗。还是自动化办公。都离不开文件操作。</p>
<h2><img decoding="async" class="alignnone size-full wp-image-1442" src="http://cdn.hyclive.cn/dixunblog/2026/03/生成Python办公插图.png" alt="" width="2730" height="1535" /></h2>
<h2>一、文件读写基础</h2>
<h3>1.1 打开文件的正确方式</h3>
<p>Python 使用 <code>open()</code> 函数打开文件。推荐使用 <code>with</code> 语句。它会自动关闭文件：</p>
<pre><code class="language-python"># 推荐方式 - with 语句自动关闭文件
with open('data.txt', 'r', encoding='utf-8') as f:
    content = f.read()
# 文件自动关闭。无需手动 f.close()

# 不推荐 - 需要手动关闭
f = open('data.txt', 'r', encoding='utf-8')
content = f.read()
f.close()  # 忘记关闭会导致资源泄漏</code></pre>
<h3>1.2 文件打开模式详解</h3>
<table class="wp-block-table">
<thead>
<tr>
<th>模式</th>
<th>说明</th>
<th>文件不存在</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>'r'</code></td>
<td>只读（默认）</td>
<td>报错</td>
</tr>
<tr>
<td><code>'w'</code></td>
<td>写入（清空原文件）</td>
<td>创建新文件</td>
</tr>
<tr>
<td><code>'a'</code></td>
<td>追加（在末尾添加）</td>
<td>创建新文件</td>
</tr>
<tr>
<td><code>'x'</code></td>
<td>独占创建</td>
<td>报错（如果已存在）</td>
</tr>
<tr>
<td><code>'b'</code></td>
<td>二进制模式</td>
<td>配合其他模式使用</td>
</tr>
<tr>
<td><code>'t'</code></td>
<td>文本模式（默认）</td>
<td>配合其他模式使用</td>
</tr>
</tbody>
</table>
<h3>1.3 读取文件的三种方法</h3>
<pre><code class="language-python"># 方法 1：read() - 读取整个文件
with open('data.txt', 'r', encoding='utf-8') as f:
    content = f.read()  # 返回字符串
    print(f"文件大小：{len(content)} 字节")

# 方法 2：readline() - 逐行读取
with open('data.txt', 'r', encoding='utf-8') as f:
    line1 = f.readline()  # 读取第一行
    line2 = f.readline()  # 读取第二行
    print(f"第一行：{line1.strip()}")

# 方法 3：readlines() - 读取所有行到列表
with open('data.txt', 'r', encoding='utf-8') as f:
    lines = f.readlines()  # 返回字符串列表
    print(f"共 {len(lines)} 行")
    for i, line in enumerate(lines, 1):
        print(f"第{i}行：{line.strip()}")

# 推荐：直接迭代文件对象（最省内存）
with open('data.txt', 'r', encoding='utf-8') as f:
    for line_num, line in enumerate(f, 1):
        print(f"第{line_num}行：{line.strip()}")</code></pre>
<h3>1.4 写入文件的多种方式</h3>
<pre><code class="language-python"># 写入模式（会清空原文件）
with open('output.txt', 'w', encoding='utf-8') as f:
    f.write("第一行内容\n")
    f.write("第二行内容\n")
    f.write("第三行内容\n")

# 追加模式（在末尾添加）
with open('output.txt', 'a', encoding='utf-8') as f:
    f.write("追加的内容\n")

# 一次性写入多行
lines = ["苹果\n", "香蕉\n", "橙子\n"]
with open('fruits.txt', 'w', encoding='utf-8') as f:
    f.writelines(lines)  # 注意：需要自己添加换行符

# 使用 print 写入文件
with open('output.txt', 'w', encoding='utf-8') as f:
    print("第一行", file=f)
    print("第二行", file=f)
    print(f"变量值：{42}", file=f)</code></pre>
<h2>二、pathlib &#8211; 现代化的路径操作</h2>
<h3>2.1 Path 对象基础</h3>
<pre><code class="language-python">from pathlib import Path

# 创建路径对象
p = Path('/home/user/documents/report.txt')

# 路径组成部分
print(p.parent)        # /home/user/documents（父目录）
print(p.name)          # report.txt（文件名）
print(p.stem)          # report（不含扩展名）
print(p.suffix)        # .txt（扩展名）
print(p.suffixes)      # ['.txt']（所有扩展名）

# 路径拼接（推荐方式）
base = Path('/home/user')
subdir = base / 'documents' / '2026'
file_path = subdir / 'report.txt'
print(file_path)  # /home/user/documents/2026/report.txt</code></pre>
<h3>2.2 路径判断与转换</h3>
<pre><code class="language-python">from pathlib import Path

p = Path('/home/user/documents')

# 路径判断
print(p.exists())        # 是否存在
print(p.is_file())       # 是否是文件
print(p.is_dir())        # 是否是目录
print(p.is_absolute())   # 是否是绝对路径

# 路径转换
print(p.absolute())      # 转为绝对路径
print(p.resolve())       # 解析符号链接后的绝对路径
print(p.relative_to('/home/user'))  # documents

# 获取当前工作目录
cwd = Path.cwd()
print(f"当前目录：{cwd}")

# 获取家目录
home = Path.home()
print(f"家目录：{home}")</code></pre>
<h2>三、批量处理文件实战</h2>
<h3>3.1 遍历目录树</h3>
<pre><code class="language-python">import os
from pathlib import Path

# 方法 1：os.walk() - 遍历目录树
for root, dirs, files in os.walk('./documents'):
    print(f"当前目录：{root}")
    print(f"子目录：{dirs}")
    print(f"文件：{files}")
    print("-" * 40)

# 方法 2：Path.glob() - 模式匹配
doc_dir = Path('./documents')

# 查找所有.txt 文件
txt_files = list(doc_dir.glob('*.txt'))
print(f"找到 {len(txt_files)} 个 txt 文件")

# 递归查找所有子目录中的.txt 文件
all_txt = list(doc_dir.rglob('*.txt'))
print(f"递归找到 {len(all_txt)} 个 txt 文件")

# 查找特定模式的文件
py_files = list(doc_dir.glob('**/*.py'))  # ** 表示递归
print(f"找到 {len(py_files)} 个 Python 文件")</code></pre>
<h3>3.2 批量重命名文件</h3>
<pre><code class="language-python">from pathlib import Path

# 批量重命名：给所有文件添加前缀
doc_dir = Path('./documents')
for file in doc_dir.glob('*.txt'):
    new_name = f"backup_{file.name}"
    file.rename(file.parent / new_name)
    print(f"重命名：{file.name} -&gt; {new_name}")

# 批量修改扩展名
for file in doc_dir.glob('*.txt'):
    new_name = file.with_suffix('.md')
    file.rename(new_name)
    print(f"修改扩展名：{file.name} -&gt; {new_name.name}")

# 按序号重命名
for i, file in enumerate(doc_dir.glob('*.md'), 1):
    new_name = file.parent / f"document_{i:03d}.md"
    file.rename(new_name)
    print(f"重命名：{file.name} -&gt; {new_name.name}")</code></pre>
<h3>3.3 批量读取与处理</h3>
<pre><code class="language-python">from pathlib import Path

# 批量读取多个文件并合并
doc_dir = Path('./documents')
all_content = []

for file in sorted(doc_dir.glob('*.txt')):
    with open(file, 'r', encoding='utf-8') as f:
        content = f.read()
        all_content.append(f"=== {file.name} ===\n{content}")

# 合并写入新文件
with open('merged.txt', 'w', encoding='utf-8') as f:
    f.write('\n'.join(all_content))

print(f"已合并 {len(all_content)} 个文件到 merged.txt")

# 批量统计文件信息
print("\n文件统计：")
for file in sorted(doc_dir.glob('*.txt')):
    stat = file.stat()
    size_kb = stat.st_size / 1024
    print(f"{file.name}: {size_kb:.2f} KB")</code></pre>
<h3>3.4 文件内容搜索与替换</h3>
<pre><code class="language-python">from pathlib import Path
import re

# 批量搜索包含特定关键词的文件
doc_dir = Path('./documents')
keyword = "Python"
matched_files = []

for file in doc_dir.glob('*.txt'):
    with open(file, 'r', encoding='utf-8') as f:
        content = f.read()
        if keyword in content:
            matched_files.append(file.name)
            count = content.count(keyword)
            print(f"{file.name}: 找到 {count} 处匹配")

print(f"\n共 {len(matched_files)} 个文件包含'{keyword}'")

# 批量替换文本
old_text = "旧版本"
new_text = "新版本"

for file in doc_dir.glob('*.txt'):
    with open(file, 'r', encoding='utf-8') as f:
        content = f.read()
    
    if old_text in content:
        new_content = content.replace(old_text, new_text)
        with open(file, 'w', encoding='utf-8') as f:
            f.write(new_content)
        print(f"已更新：{file.name}")</code></pre>
<h2>四、高级文件操作</h2>
<h3>4.1 文件复制、移动与删除</h3>
<pre><code class="language-python">from pathlib import Path
import shutil

# 复制文件
src = Path('./source.txt')
dst = Path('./backup/source_copy.txt')
dst.parent.mkdir(parents=True, exist_ok=True)  # 创建目录
shutil.copy2(src, dst)  # copy2 保留元数据
print(f"已复制：{src} -&gt; {dst}")

# 复制整个目录
shutil.copytree('./docs', './docs_backup')
print("已复制整个目录")

# 移动文件
src = Path('./old_location/file.txt')
dst = Path('./new_location/file.txt')
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.move(src, dst)
print(f"已移动：{src} -&gt; {dst}")

# 删除文件
Path('./temp.txt').unlink()  # 删除单个文件
print("已删除 temp.txt")

# 删除整个目录
shutil.rmtree('./old_backup')
print("已删除目录")</code></pre>
<h3>4.2 临时文件处理</h3>
<pre><code class="language-python">import tempfile
from pathlib import Path

# 创建临时文件
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt') as f:
    temp_path = f.name
    f.write("临时内容")
    print(f"临时文件：{temp_path}")

# 使用临时文件
with open(temp_path, 'r') as f:
    print(f"读取临时文件：{f.read()}")

# 清理临时文件
Path(temp_path).unlink()
print("已清理临时文件")

# 创建临时目录
with tempfile.TemporaryDirectory() as temp_dir:
    print(f"临时目录：{temp_dir}")
    # 在临时目录中操作
    temp_file = Path(temp_dir) / 'test.txt'
    temp_file.write_text("测试内容")
# 退出 with 后自动清理临时目录</code></pre>
<h3>4.3 文件编码处理</h3>
<pre><code class="language-python">import chardet

# 检测文件编码
def detect_encoding(file_path):
    with open(file_path, 'rb') as f:
        result = chardet.detect(f.read(10000))  # 读取前 10KB
    return result['encoding']

# 批量转换编码
from pathlib import Path

doc_dir = Path('./documents')
for file in doc_dir.glob('*.txt'):
    # 检测编码
    encoding = detect_encoding(file)
    print(f"{file.name}: 检测到编码 {encoding}")
    
    # 读取并转换为 UTF-8
    with open(file, 'r', encoding=encoding) as f:
        content = f.read()
    
    # 写回 UTF-8
    with open(file, 'w', encoding='utf-8') as f:
        f.write(content)
    print(f"已转换：{file.name}")</code></pre>
<h2>五、实战项目</h2>
<h3>5.1 日志文件分析器</h3>
<pre><code class="language-python">from pathlib import Path
from collections import Counter
import re

def analyze_log(log_path):
    '''分析日志文件'''
    log_file = Path(log_path)
    
    error_count = 0
    warning_count = 0
    error_lines = []
    
    with open(log_file, 'r', encoding='utf-8') as f:
        for line_num, line in enumerate(f, 1):
            if 'ERROR' in line:
                error_count += 1
                error_lines.append((line_num, line.strip()))
            elif 'WARNING' in line:
                warning_count += 1
    
    print(f"日志分析结果：")
    print(f"  错误数：{error_count}")
    print(f"  警告数：{warning_count}")
    print(f"\n最新错误：")
    for line_num, line in error_lines[-5:]:
        print(f"  行{line_num}: {line}")

# 使用示例
analyze_log('./app.log')</code></pre>
<h3>5.2 批量图片重命名</h3>
<pre><code class="language-python">from pathlib import Path
from datetime import datetime

def rename_photos(photo_dir, prefix="IMG"):
    '批量重命名照片'
    photo_path = Path(photo_dir)
    
    # 获取所有图片文件
    images = list(photo_path.glob('*.jpg')) + list(photo_path.glob('*.png'))
    images.sort(key=lambda p: p.stat().st_mtime)  # 按修改时间排序
    
    for i, img in enumerate(images, 1):
        # 生成新文件名
        date_str = datetime.fromtimestamp(img.stat().st_mtime).strftime('%Y%m%d')
        new_name = f"{prefix}_{date_str}_{i:04d}{img.suffix}"
        new_path = img.parent / new_name
        
        # 重命名
        img.rename(new_path)
        print(f"{img.name} -&gt; {new_name}")

# 使用示例
rename_photos('./photos', 'VACATION')</code></pre>
<h3>5.3 文件备份工具</h3>
<pre><code class="language-python">from pathlib import Path
import shutil
from datetime import datetime

def backup_files(source_dir, backup_dir, patterns=None):
    '备份指定类型的文件'
    source = Path(source_dir)
    backup = Path(backup_dir)
    
    # 创建带时间戳的备份目录
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    backup_path = backup / f"backup_{timestamp}"
    backup_path.mkdir(parents=True, exist_ok=True)
    
    # 默认备份所有文件
    if patterns is None:
        patterns = ['*']
    
    # 复制文件
    copied_count = 0
    for pattern in patterns:
        for file in source.glob(pattern):
            if file.is_file():
                dest = backup_path / file.name
                shutil.copy2(file, dest)
                copied_count += 1
    
    print(f"备份完成：{copied_count} 个文件")
    print(f"备份位置：{backup_path}")
    return backup_path

# 使用示例
backup_files('./documents', './backups', ['*.txt', '*.docx', '*.pdf'])</code></pre>
<h2>六、常见错误与解决</h2>
<h3>6.1 文件不存在错误</h3>
<pre><code class="language-python">from pathlib import Path

# 错误：文件不存在会报错
# with open('not_exist.txt', 'r') as f:
#     content = f.read()  # FileNotFoundError!

# 解决：先检查是否存在
file = Path('not_exist.txt')
if file.exists():
    content = file.read_text()
else:
    print("文件不存在。创建新文件")
    file.write_text("初始内容")

# 或使用异常处理
try:
    content = file.read_text()
except FileNotFoundError:
    print("文件不存在。使用默认内容")
    content = "默认内容"</code></pre>
<h3>6.2 编码错误</h3>
<pre><code class="language-python"># 错误：编码不匹配
# with open('file.txt', 'r', encoding='ascii') as f:
#     content = f.read()  # UnicodeDecodeError!

# 解决：使用正确的编码
with open('file.txt', 'r', encoding='utf-8') as f:
    content = f.read()

# 或忽略错误
with open('file.txt', 'r', encoding='utf-8', errors='ignore') as f:
    content = f.read()

# 或替换错误字符
with open('file.txt', 'r', encoding='utf-8', errors='replace') as f:
    content = f.read()</code></pre>
<h3>6.3 权限错误</h3>
<pre><code class="language-python">from pathlib import Path

# 错误：没有写入权限
# Path('/root/protected.txt').write_text("内容")  # PermissionError!

# 解决：检查权限或选择其他目录
file = Path('./user_file.txt')
try:
    file.write_text("内容")
except PermissionError:
    print("没有权限。尝试其他目录")
    file = Path.home() / 'file.txt'
    file.write_text("内容")</code></pre>
<h2>七、最佳实践</h2>
<ol>
<li><strong>始终使用 with 语句</strong>：自动关闭文件。避免资源泄漏</li>
<li><strong>明确指定编码</strong>：始终使用 <code>encoding='utf-8'</code></li>
<li><strong>使用 pathlib</strong>：比 os.path 更现代、更易用</li>
<li><strong>大文件分块读取</strong>：避免一次性加载到内存
<pre><code class="language-python">with open('large_file.txt', 'r') as f:
    for chunk in iter(lambda: f.read(8192), ''):
        process(chunk)</code></pre>
</li>
<li><strong>先创建目录再写入</strong>：
<pre><code class="language-python">output = Path('./output/subdir/file.txt')
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text("内容")</code></pre>
</li>
</ol>
<h2>八、总结与练习</h2>
<p>今天我们深入学习了 Python 文件处理的各个方面。建议：</p>
<ol>
<li><strong>掌握基础</strong>：open()、read()、write()、with 语句</li>
<li><strong>熟练使用 pathlib</strong>：现代化的路径操作</li>
<li><strong>理解编码</strong>：UTF-8 是默认选择</li>
<li><strong>多实践</strong>：通过实际项目巩固知识</li>
</ol>
<h3>课后练习</h3>
<ol>
<li>编写脚本。统计目录下所有代码文件的总行数</li>
<li>实现一个简单的文件搜索工具。支持关键词搜索</li>
<li>编写批量重命名工具。支持添加前缀、后缀、序号</li>
<li>实现日志分析器。提取错误和警告信息</li>
<li>创建自动备份脚本。定期备份重要文件</li>
</ol>
<hr />
<p><em>关注我们获取更多 Python 实战教程！下节课我们将学习 Python 网络爬虫入门。</em></p>
<p><a href="https://www.dixunblog.cn/1454.html">Python 文件批量处理与自动化 &#8211; 进阶篇</a>最先出现在<a href="https://www.dixunblog.cn">帝讯博客</a>。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.dixunblog.cn/1454.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Python 自动化办公实战：Excel 处理 &#8211; 基础篇</title>
		<link>https://www.dixunblog.cn/1453.html</link>
					<comments>https://www.dixunblog.cn/1453.html#respond</comments>
		
		<dc:creator><![CDATA[小编]]></dc:creator>
		<pubDate>Mon, 30 Mar 2026 02:05:55 +0000</pubDate>
				<category><![CDATA[技术教程]]></category>
		<category><![CDATA[编程代码]]></category>
		<category><![CDATA[Python 教程]]></category>
		<category><![CDATA[python-excel]]></category>
		<category><![CDATA[代码教程]]></category>
		<guid isPermaLink="false">https://www.dixunblog.cn/1453.html</guid>

					<description><![CDATA[<p>欢迎来到今天的 Python 实战教程！今天我们来学习 Python 自动化办公之 Excel 处理。</p>
<p>一、环境准备</p>
<p>1.1 安装库<br />
<code class="language-bash">pip install openpyxl pandas xlrd xlwt</p>
<p>1.2 库的选择</p>
<p><strong>openpy...</p>
<p><a href="https://www.dixunblog.cn/1453.html">Python 自动化办公实战：Excel 处理 &#8211; 基础篇</a>最先出现在<a href="https://www.dixunblog.cn">帝讯博客</a>。</p>
]]></description>
										<content:encoded><![CDATA[<p>欢迎来到今天的 Python 实战教程！今天我们来学习 Python 自动化办公之 Excel 处理。</p>
<h2><img decoding="async" class="alignnone size-full wp-image-1442" src="http://cdn.hyclive.cn/dixunblog/2026/03/生成Python办公插图.png" alt="" width="2730" height="1535" /></h2>
<h2>一、环境准备</h2>
<h3>1.1 安装库</h3>
<pre><code class="language-bash">pip install openpyxl pandas xlrd xlwt</code></pre>
<h3>1.2 库的选择</h3>
<ul>
<li><strong>openpyxl</strong>：读写.xlsx 文件</li>
<li><strong>pandas</strong>：数据处理和分析</li>
<li><strong>xlrd/xlwt</strong>：读写.xls 文件（旧格式）</li>
</ul>
<h2>二、读取 Excel 文件</h2>
<h3>2.1 使用 openpyxl</h3>
<pre><code class="language-python">from openpyxl import load_workbook

# 加载工作簿
wb = load_workbook('data.xlsx')

# 选择工作表
ws = wb['Sheet1']

# 读取单元格
value = ws['A1'].value

# 遍历行
for row in ws.iter_rows():
    for cell in row:
        print(cell.value)</code></pre>
<h3>2.2 使用 pandas</h3>
<pre><code class="language-python">import pandas as pd

# 读取 Excel
df = pd.read_excel('data.xlsx')

# 查看数据
print(df.head())
print(df.columns)

# 选择列
names = df['姓名']</code></pre>
<h2>三、写入 Excel 文件</h2>
<h3>3.1 创建新文件</h3>
<pre><code class="language-python">from openpyxl import Workbook

wb = Workbook()
ws = wb.active
ws.title = "数据表"

# 写入数据
ws['A1'] = "姓名"
ws['B1'] = "年龄"
ws.append(["张三", 25])
ws.append(["李四", 28])

wb.save('output.xlsx')</code></pre>
<h3>3.2 使用 pandas 写入</h3>
<pre><code class="language-python">import pandas as pd

data = {
    '姓名': ['张三', '李四'],
    '年龄': [25, 28],
    '城市': ['北京', '上海']
}

df = pd.DataFrame(data)
df.to_excel('output.xlsx', index=False)</code></pre>
<h2>四、数据处理实战</h2>
<h3>4.1 数据筛选</h3>
<pre><code class="language-python"># 筛选年龄大于 25 的记录
filtered = df[df['年龄'] &gt; 25]

# 多条件筛选
filtered = df[(df['年龄'] &gt; 25) &amp; (df['城市'] == '北京')]</code></pre>
<h3>4.2 数据统计</h3>
<pre><code class="language-python"># 平均值
avg_age = df['年龄'].mean()

# 分组统计
grouped = df.groupby('城市')['年龄'].mean()</code></pre>
<h3>4.3 数据合并</h3>
<pre><code class="language-python"># 合并两个 Excel
df1 = pd.read_excel('file1.xlsx')
df2 = pd.read_excel('file2.xlsx')

# 横向合并
merged = pd.merge(df1, df2, on='姓名')

# 纵向合并
combined = pd.concat([df1, df2])</code></pre>
<h2>五、批量处理</h2>
<h3>5.1 批量读取</h3>
<pre><code class="language-python">import os
import pandas as pd

files = [f for f in os.listdir('.') if f.endswith('.xlsx')]
all_data = []

for file in files:
    df = pd.read_excel(file)
    all_data.append(df)

combined = pd.concat(all_data)</code></pre>
<h3>5.2 批量写入</h3>
<pre><code class="language-python">departments = ['销售部', '技术部', '财务部']

for dept in departments:
    df = get_department_data(dept)
    df.to_excel(f'{dept}_报表.xlsx', index=False)</code></pre>
<h2>六、格式化与样式</h2>
<pre><code class="language-python">from openpyxl.styles import Font, PatternFill

# 设置字体
ws['A1'].font = Font(bold=True, color='FF0000')

# 设置背景色
ws['A1'].fill = PatternFill(start_color='FFFF00', fill_type='solid')

# 设置列宽
ws.column_dimensions['A'].width = 20</code></pre>
<h2>七、总结</h2>
<p>Python 处理 Excel 可以大幅提升办公效率。建议多实践。</p>
<hr />
<p><em>关注我们获取更多 Python 实战教程！</em></p>
<p><a href="https://www.dixunblog.cn/1453.html">Python 自动化办公实战：Excel 处理 &#8211; 基础篇</a>最先出现在<a href="https://www.dixunblog.cn">帝讯博客</a>。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.dixunblog.cn/1453.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
