注释
# 这是单行注释
"""
这是多行注释
可以写多行文字
"""
变量和数据类型
内置基本数据类型
- 整数 (int): 用于表示没有小数部分的数字,例如 -1, 0, 1, 100 等
- 浮点数 (float): 用于表示带有小数部分的数字,例如 3.14, 2.718
- 字符串 (str): 用于表示文本信息,必须使用引号(单引号或双引号)括起来,例如 “Hello, Python”。
- 布尔值 (bool): 用于表示真或假,取值为 True 或 False。
# 定义不同类型的变量
age = 25 # 整数
pi = 3.14 # 浮点数
name = "Alice" # 字符串
is_student = True # 布尔值
# 打印变量的值及其类型
print("Age:", age, "Type:", type(age))
print("Pi:", pi, "Type:", type(pi))
print("Name:", name, "Type:", type(name))
print("Is Student:", is_student, "Type:", type(is_student))
Age: 25 Type: <class 'int'>
Pi: 3.14 Type: <class 'float'>
Name: Alice Type: <class 'str'>
Is Student: True Type: <class 'bool'>
基本数据结构
列表(List)
列表是有序的序列,可以存储任意数量的元素,可以包含不同类型的元素,列表是动态的,可以在程序运行时添加和删除元素
- 创建列表
列表可以通过 [] 来创建,并且元素之间用,分隔
# 创建一个空列表
empty_list = []
# 创建一个包含不同数据类型的列表
mixed_list = [1,'hello', 3.14, True]
# 创建一个包含整数的列表
numbers = [1,2,3,4,5]
- 访问列表元素
可以通过索引来访问列表中的元素,Python中的索引从0开始
numbers = [1,2,3,4,5]
# 访问第一个元素
first_element = numbers[0] # 输出 1
# 访问最后一个元素
last_element = numbers[-1] # 输出 5
# 访问中间的元素
middle_element = numbers[2] # 输出 3
- 修改列表元素
可以直接通过索引来修改列表中的元素
# 修改第一个元素
numbers = [1,2,3,4,5]
numbers[0] = 10
print(numbers[0])
10
- 切片列表
可以使用切片来获取列表的一部分
# 获取前三个元素
first_three = numbers[:3] # 输出 [10, 2, 3]
# 获取后两个元素
last_two = numbers[-2:] # 输出 [4, 5]
- 添加元素到列表
可以使用 append() 方法将元素添加到列表末尾,或者使用insert()在指定位置插入元素
# 在末尾添加一个元素
numbers.append(6) # 现在 numbers 为 [10, 2, 3, 4, 5, 6]
# 在索引 1 处插入一个新元素
numbers.insert(1, 11) # 现在 numbers 为 [10, 11, 2, 3, 4, 5, 6]
- 删除列表元素
可以使用 remove() 方法删除列表中的元素,也可以使用del语句删除指定索引的元素
# 移除值为 11 的元素
numbers.remove(11) # 现在 numbers 为 [10, 2, 3, 4, 5, 6]
# 删除索引为 0 的元素
del numbers[0] # 现在 numbers 为 [2, 3, 4, 5, 6]
- 其他列表方法
列表还提供了许多其他有用的方法,如 extend(),pop(),index(),count(),sort(), reverse()等
# 扩展列表
more_numbers = [7, 8, 9]
numbers.extend(more_numbers) # 现在 numbers 为 [2, 3, 4, 5, 6, 7, 8, 9]
# 弹出最后一个元素
last_number = numbers.pop() # last_number 为 9, numbers 为 [2, 3, 4, 5, 6, 7, 8]
# 查找元素的索引
index_of_5 = numbers.index(5) # index_of_5 为 3
# 计算元素出现次数
count_of_5 = numbers.count(5) # count_of_5 为 1
# 排序列表
numbers.sort() # 现在 numbers 为 [2, 3, 4, 5, 6, 7, 8]
# 反转列表
numbers.reverse() # 现在 numbers 为 [8, 7, 6, 5, 4, 3, 2]
元组(Tuple)
元组是有序且不可变的序列,一旦创建,其中元素不可修改
- 创建元组
元组可以通过圆括号()来创建,元素之间用逗号,分隔
# 创建一个空元组
empty_tuple = ()
# 创建一个包含不同数据类型的元组
mixed_tuple = (1, 'hello', 3.14, True)
# 创建一个只包含一个元素的元组
single_element_tuple = ('only one element',) # 注意结尾的逗号
- 访问元组元素
可以通过索引来访问元组中的元素,Python中的索引从0开始
# 访问第一个元素
first_element = mixed_tuple[0] # 输出 1
# 访问最后一个元素
last_element = mixed_tuple[-1] # 输出 True
# 访问中间的元素
middle_element = mixed_tuple[2] # 输出 3.14
- 元组切片
可以使用切片来获取元组的一部分
# 获取前三个元素
first_three = mixed_tuple[:3] # 输出 (1, 'hello', 3.14)
# 获取后两个元素
last_two = mixed_tuple[-2:] # 输出 (3.14, True)
- 元组的不可变性
由于元组是不可变的,所以不能直接修改元组中的元素
# 尝试修改元组中的元素会导致错误
# mixed_tuple[0] = 2 # TypeError: 'tuple' object does not support item assignment
但是,如果元组中的某个元素本身是可变的(例如列表),那么可以通过这个元素进行修改。
# 创建一个包含列表的元组
mutable_tuple = (1, ['a', 'b'], 3)
# 修改列表中的元素
mutable_tuple[1][0] = 'z' # 现在 mutable_tuple 为 (1, ['z', 'b'], 3)
- 元组的常用操作
元组提供了一些内置的方法和操作,如len(),count(),index()等
# 获取元组的长度
length = len(mixed_tuple) # 输出 4
# 计算元素出现的次数
count_of_hello = mixed_tuple.count('hello') # 输出 1
# 查找元素的索引
index_of_hello = mixed_tuple.index('hello') # 输出 1
- 元组的拼接
可以使用 + 运算符来拼接两个元组
# 创建两个元组
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
# 拼接两个元组
combined_tuple = tuple1 + tuple2 # 结果为 (1, 2, 3, 4, 5, 6)
- 元组的重复
可以使用 * 运算符来重复元组
# 重复元组
repeated_tuple = tuple1 * 2 # 结果为 (1, 2, 3, 1, 2, 3)
- 元组解包
可以使用解包来将元组中的元素分配给多个变量
# 解包元组
a, b, c, d = mixed_tuple # a=1, b='hello', c=3.14, d=True
字典(Dictionary)
字典是键值对的集合,字典是无序的,可变的,其中每一个键都是唯一的,每个键都关联一个值
- 创建字典
字典可以通过花括号{}来创建,键值对之间用 : 分隔,每对键值对之间用逗号 , 分隔
# 创建一个空字典
empty_dict = {}
# 创建一个包含键值对的字典
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
- 访问字典元素
可以通过键来访问字典中的值
# 访问字典中的元素
name = person['name'] # 输出 'Alice'
age = person.get('age') # 输出 25
- 修改字典元素
可以直接通过键来修改字典中的值
# 修改字典中的元素
person['age'] = 26 # 现在 person 为 {'name': 'Alice', 'age': 26, 'city': 'New York'}
- 添加新的键值对
可以直接通过键来添加新的键值对
# 添加新的键值对
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
person['job'] = 'Engineer' # 现在 person 为 {'name': 'Alice', 'age': 25, 'city': 'New York', 'job': 'Engineer'}
- 删除字典元素
可以使用 del 语句来删除字典中的键值对
# 删除字典中的键值对
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
del person['city'] # 现在 person 为 {'name': 'Alice', 'age': 26}
- 字典的遍历
可以使用 for 循环来遍历字典中的键,值或键值对
# 遍历字典中的键
for key in person:
print(key)
# 遍历字典中的值
for value in person.values():
print(value)
# 遍历字典中的键值对
for key, value in person.items():
print(f"{key}: {value}")
name
age
Alice
25
name: Alice
age: 25
- 字典的其他方法
字典还提供了一些内置的方法,如 keys(), values(), items(), clear(), update(), copy() 等
# 获取所有键
keys = person.keys() # 输出 dict_keys(['name', 'age', 'job'])
# 获取所有值
values = person.values() # 输出 dict_values(['Alice', 26, 'Engineer'])
# 获取所有键值对
items = person.items() # 输出 dict_items([('name', 'Alice'), ('age', 26), ('job', 'Engineer')])
# 清空字典
person.clear() # 现在 person 为空字典 {}
# 更新字典
person.update({'name': 'Bob', 'age': 30}) # 现在 person 为 {'name': 'Bob', 'age': 30}
# 复制字典
new_person = person.copy() # new_person 为 {'name': 'Bob', 'age': 30}
- 字典推导式
可以使用字典推导式来创建新的字典
# 创建一个新的字典,其中的值是原字典值的平方
squared_person = {k: v**2 for k, v in person.items() if isinstance(v, int)}
集合(Set)
集合是无序且不重复的元素集合,可以执行并集,交集,差集和对称差集等
- 创建集合
集合可以通过花括号{} 或set() 函数来创建, 需要注意的是,创建一个空集合必须使用set(),因为{}会被解释为一个空字典
# 创建一个空集合
empty_set = set()
# 创建一个包含元素的集合
fruits = {'apple', 'banana', 'cherry'}
# 从列表创建集合
numbers = set([1, 2, 2, 3, 4, 4])
- 集合的去重
集合自动去重,因此重复的元素会被忽略
# 创建一个包含重复元素的集合
numbers_with_duplicates = {1, 2, 2, 3, 4, 4}
# 结果将是 {1, 2, 3, 4}
- 集合的添加和删除
可以使用add()方法向集合中添加元素,使用remove() 或 discard() 方法来删除元素
# 添加元素
fruits.add('orange')
# 删除元素
fruits.remove('banana') # 如果元素不存在,则会引发 KeyError
fruits.discard('banana') # 如果元素不存在,则什么也不做
- 集合的更新
可以使用update() 方法来添加多个元素,这些元素可以从另一个集合,列表或其他课迭代对象中获取
# 更新集合
fruits.update(['grape', 'mango'])
- 集合的运算
集合支持多种运算,如并集,交集,差集和对称差集等
# 创建两个集合
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# 并集
union_set = set1 | set2 # 或者使用 set1.union(set2)
# 交集
intersection_set = set1 & set2 # 或者使用 set1.intersection(set2)
# 差集
difference_set = set1 - set2 # 或者使用 set1.difference(set2)
# 对称差集
symmetric_difference_set = set1 ^ set2 # 或者使用 set1.symmetric_difference(set2)
- 集合的成员资格测试
可以使用in关键字来检查一个元素是否属于集合
set1 = {1, 2, 3, 4}
# 成员资格测试
if 5 in set1:
print("3 is in set1")
- 不可变集合(frozenset)
frozenset是一种不可变的集合类型,一旦创建就不能更改
# 创建一个不可变集合
immutable_set = frozenset([1, 2, 3])
条件语句
条件语句用于根据条件执行不同的代码块,Python条件语句包括 if 语句, if-else 语句和 if-elif-else 语句
- if 语句
if 语句是最简单的条件语句,它只有条件为真时才会执行代码块
x = 10
if x > 0:
print("x is positive")
x is positive
- if-else 语句
if-else 语句会在条件为真时执行一个代码块,在条件为假时执行另一个代码块,在条件为假时执行另一个代码块
x = 0
if x > 0:
print("x is positive")
else:
print("x is not positive")
x is not positive
- if-elif-else 语句
if-elif-else 语句可以测试多个条件
score = 85
if score >= 90:
print("Grade A")
elif score >= 80:
print("Grade B")
elif score >= 70:
print("Grade C")
else:
print("Grade D")
Grade B
- 条件表达式
在条件语句中,可以使用比较运算符(如 ==, !=, >, <, >=, <=)和其他逻辑运算符(如 and, or, not)来构建复杂的条件表达式。
age = 20
if age >= 18 and age <= 65:
print("You are an adult.")
else:
print("You are either a minor or a senior citizen.")
You are an adult.
- 嵌套的条件语句
条件语句可以嵌套使用,即在一个条件语句内部再包含另一个条件语句
temperature = 25
humidity = 70
if temperature > 30:
if humidity > 70:
print("It's hot and humid.")
else:
print("It's hot but dry.")
elif temperature > 20:
print("It's warm.")
else:
print("It's cool.")
It's warm.
- 条件语句的注意事项
条件表达式的真假是根据布尔值 True 和 False 来判断的。
elif 和 else 子句是可选的,可以根据需要使用 。
条件语句的缩进非常重要,因为它决定了哪些代码属于哪个代码块。
循环
for 循环
for循环是一种常用的迭代结构,用于遍历序列(如列表,元组,字典,集合,字符串)中的元素
- 基本的 for 循环
最简单的 for 循环形式是遍历一个序列中的元素
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
apple
banana
cherry
- 使用range()函数
range()函数可以生成一个整数序列,常用于控制循环次数
for i in range(5):
print(i)
0
1
2
3
4
- for 循环与 else 语句
for循环还可以与 else 子句一起使用,当循环正常结束(即没有被break语句中断)时,else子句中的代码将会执行
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
break
else:
# 循环没有被 break 中断
print(n, 'is a prime number')
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
- enumerate() 函数
enumerate() 函数可以同时获取序列中的元素及其索引
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
0 apple
1 banana
2 cherry
- zip()函数
zip()函数可以用来同时遍历多个序列
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")
Alice is 25 years old.
Bob is 30 years old.
Charlie is 35 years old.
- 嵌套的 for 循环
for 循环可以嵌套使用,即在一个 for 循环内部再包含另一个 for 循环
for row in range(5):
for col in range(5):
print('*', end='')
print()
*****
*****
*****
*****
*****
- 使用 try-except 语句处理异常
在 for 循环中可以使用 try-except 语句来处理可能出现的异常情况
numbers = [1, 2, 3, 'a', 4, 5]
for num in numbers:
try:
print(num * 2)
except TypeError:
print("Cannot multiply by 2")
2
4
6
aa
8
10
- 使用列表推导式
列表推导式是一种简洁的方式,可以在一行代码中创建新的列表
squares = [x**2 for x in range(5)]
print(squares) # 输出 [0, 1, 4, 9, 16]
[0, 1, 4, 9, 16]
- 使用 for 循环遍历字典
遍历字典时,默认遍历的是键
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
for key in person:
print(key, person[key])
name Alice
age 25
city New York
- 使用for 循环遍历字典的键值对
可以使用 items() 方法来同时获取字典中的键和值
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
for key, value in person.items():
print(key, value)
name Alice
age 25
city New York
while 循环
while循环用于重复执行一段代码,只要指定条件为真,while 循环基于条件的循环,这意味循环将继续执行,知道条件变为假
- 基本的 while 循环
最简单的 while 循环形式是基于一个条件的循环
count = 0
while count < 5:
print("Count is:", count)
count += 1
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
- 使用 breck 和 continue 语句
- break 语句用于立即退出循环
- continue 语句用于跳过当前迭代的剩余部分,并继续下一次迭代
count = 0
while count < 10:
count += 1
if count == 5:
continue
if count == 8:
break
print("Count is:", count)
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 6
Count is: 7
- while 循环与 else 子句
while 循环也可以与 else 子句一起使用,当循环正常结束(即没有被break语句中断) 时, else 子句中的代码将会被执行
count = 0
while count < 5:
print("Count is:", count)
count += 1
else:
print("Loop ended normally.")
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Loop ended normally.
- 使用 while 循环处理无限循环
有时候,可能需要一个无限循环,这种情况,可以使用一个永远为真的条件,然后再循环体内部使用 break 语句来终止循环
while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == 'quit':
break
print("You entered:", user_input)
- 使用 while 循环处理列表
while 循环可以用来处理列表中的元素, 知道列表为空或达到某个条件
numbers = [1, 2, 3, 4, 5]
index = 0
while index < len(numbers):
print("Current number is:", numbers[index])
index += 1
- 使用 while 循环处理字典
while 循环可以用来遍历字典中的键或键值对
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
keys = list(person.keys())
index = 0
while index < len(keys):
key = keys[index]
print(key, ":", person[key])
index += 1
- 使用 while 循环处理文件
while 循环可以用来逐行读取文件
with open('example.txt', 'r') as file:
line = file.readline()
while line:
print(line.strip()) # 去除行尾的换行符
line = file.readline()
- 使用while 循环处理网络请求
while 循环可以用来处理网络请求, 比如定时重试失败的请求
import requests
url = 'http://example.com/api/data'
attempts = 0
max_attempts = 3
while attempts < max_attempts:
try:
response = requests.get(url)
response.raise_for_status() # 抛出 HTTP 错误
data = response.json()
print(data)
break
except requests.RequestException as e:
print("Request failed:", e)
attempts += 1
else:
print("Failed after", max_attempts, "attempts.")
函数
允许封装一段代码,并可以多次调用这段代码来执行特定的任务,函数可以接收参数,并返回一个值,可以自定义函数,也可以使用内置函数
- 定义函数
函数定义使用 def 关键字开始,后面跟函数名和圆括号,括号内可以有参数,最后是跟一个冒号 : ,紧接着是函数体
def greet(name):
"""Print a greeting to the name."""
print(f"Hello, {name}!")
- 调用函数
- 定义了函数之后,你需要调用它来执行其中的代码
def greet(name):
"""Print a greeting to the name."""
print(f"Hello, {name}!")
greet("Alice") # 输出: Hello, Alice!
- 函数参数
函数可以接受不同类型的参数,包括位置参数, 关键字参数, 默认参数和可变参数
def add_numbers(a, b=10):
"""Add two numbers with an optional second argument."""
return a + b
result = add_numbers(5) # 使用默认值
print(result) # 输出: 15
result = add_numbers(5, 20) # 显式提供第二个参数
print(result) # 输出: 25
- 可变参数
函数可以接受任意数量的位置参数或关键字参数
def sum_numbers(*args):
"""Sum an arbitrary number of arguments."""
return sum(args)
result = sum_numbers(1, 2, 3, 4, 5)
print(result) # 输出: 15
def print_keywords(**kwargs):
"""Print keyword arguments."""
for key, value in kwargs.items():
print(f"{key}: {value}")
print_keywords(name="Alice", age=25)
# 输出:
# name: Alice
# age: 25
- 返回值
函数可以返回一个值或多个值
def get_name_and_age():
"""Return a tuple containing name and age."""
return ("Alice", 25)
name, age = get_name_and_age()
print(name, age) # 输出: Alice 25
- 匿名函数(lambda 函数)
匿名函数或 lambda 函数是一种简化版的函数定义,主要用于简单的计算任务
multiply = lambda x, y: x * y
result = multiply(5, 6)
print(result) # 输出: 30
- 内置函数
Python提供了很多内置函数,例如 len(), print(), type(), sorted(), sum(), map(). filter()等
numbers = [1, 2, 3, 4, 5]
print(len(numbers)) # 输出: 5
print(sum(numbers)) # 输出: 15
- 文档字符串
文档字符串(docstrings) 是函数的第一行注释,用于描述函数的用法和功能
def greet(name):
"""Print a greeting to the name.
Args:
name (str): The name to greet.
"""
print(f"Hello, {name}!")
help(greet)
# 输出:
# Help on function greet in module __main__:
#
# greet(name)
# Print a greeting to the name.
#
# Args:
# name (str): The name to greet.
- 局部变量和全局变量
函数内部定义的变量是局部变量,而在函数外部定义的变量是全局变量
x = 10 # 全局变量
def change_x():
global x # 声明使用全局变量
x = 20
change_x()
print(x) # 输出: 20
- 递归函数
递归函数是指在其定义中调用自己的函数,适用于解决某些特定问题
def factorial(n):
"""Calculate the factorial of n."""
if n == 0:
return 1
else:
return n * factorial(n-1)
print(factorial(5)) # 输出: 120
类和对象
Python 是面向对象的编程语言,可以定义类和创建对象
- 定义类
类定义使用 class 关键字开始, 后面跟着类名,通常首字母大写,类体包含属性和方法
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print(f"Name: {self.name}, Age: {self.age}")
- 实例化对象
创建类的实例,即创建一个对象
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
- 访问属性和方法
通过对象可以访问类的属性和方法
person1.display() # 输出: Name: Alice, Age: 25
print(person2.name) # 输出: Bob
- 构造函数 init
构造函数__init__ 在创建对象时自动调用,用于初始化对象的状态
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
- 实例属性
实例属性是每个对象特有的属性,他们通过 self 关键字访问
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
- 类属性
类属性是所有对象共享的属性,它们直接通过类型访问
class Person:
species = "Homo sapiens"
def __init__(self, name, age):
self.name = name
self.age = age
print(Person.species) # 输出: Homo sapiens
- 方法
方法是类中的函数,它们通过 self 参数访问对象的状态
class Person:
def display(self):
print(f"Name: {self.name}, Age: {self.age}")
- 修改属性
对象的属性可以通过赋值来修改
person1 = Person("Alice", 25)
person1.age = 26
print(person1.age) # 输出: 26
- 删除属性
可以使用 del 语句删除对象的属性
person1 = Person("Alice", 25)
del person1.age
# person1.age # 这里会抛出 AttributeError
- 删除对象
可以使用 del 语句删除对象
person1 = Person("Alice", 25)
del person1
# person1.display() # 这里会抛出 NameError
- 继承
子类可以从父类继承属性和方法
class Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age)
self.grade = grade
def display(self):
super().display()
print(f"Grade: {self.grade}")
student1 = Student("Charlie", 18, "A")
student1.display() # 输出: Name: Charlie, Age: 18, Grade: A
- 多态
多态允许子类重写父类的方法,从而表现出不同的行为
class Teacher(Person):
def display(self):
print(f"Teacher: {self.name}, Age: {self.age}")
teacher1 = Teacher("David", 40)
teacher1.display() # 输出: Teacher: David, Age: 40
文件操作
Python 可以方便地进行文件读取,写入,追加以及关闭等基本操作
- 打开文件
使用 open() 函数打开文件,这个函数接受两个参数: 文件名和模式
模式说明
- ‘r’:只读模式,默认模式。
- ‘w’:写入模式,如果文件不存在则创建新文件;如果文件已存在,则覆盖原有内容
- ‘a’:追加模式,如果文件不存在则创建新文件;如果文件已存在,则在文件末尾添加内容*
- ‘b’:二进制模式,用于读写二进制文* 件
- ‘+’:更新模式,用于读写操作
file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()
- 使用 with 语句
使用 with 语句可以安全的打开和关闭文件,即使在文件操作过程中发生异常,文件也会被正确关闭
with open('example.txt', 'r') as file:
content = file.read()
print(content)
- 读取文件
- read(size):读取指定数量的字符,默认读取整个文件
- readline():读取一行
- readlines():读取所有行并返回列表
with open('example.txt', 'r') as file:
first_line = file.readline()
all_lines = file.readlines()
print(first_line)
print(all_lines)
- 写入文件
- write(string):写入字符串到文件
- writelines(list):写入一个字符串列表到文件
with open('output.txt', 'w') as file:
file.write("Hello, world!\n")
file.writelines(["First line\n", "Second line\n"])
- 追加文件
使用 ‘a’ 模式追加内容到文件
with open('output.txt', 'a') as file:
file.write("Additional text.\n")
- 文件指针
- tell():返回文件当前位置。
- seek(offset, whence):改变文件当前位置。
with open('example.txt', 'r') as file:
print(file.tell()) # 输出当前位置
file.seek(10) # 移动到第10个字符
print(file.read(5)) # 从当前位置读取5个字符
- 文件的其他操作
- os 模块提供了许多文件和目录操作的函数。
- os.path 模块包含了路径操作的函数。
import os
# 获取文件大小
size = os.path.getsize('example.txt')
print(size)
# 列出目录下的文件
files = os.listdir('.')
print(files)
- 文件的复制
使用 shutil 模块可以方便地复制文件。
import shutil
shutil.copy('example.txt', 'example_copy.txt')
- 文件的压缩和解压
使用 zipfile 模块可以压缩和解压文件。
import zipfile
# 压缩文件
with zipfile.ZipFile('archive.zip', 'w') as zipf:
zipf.write('example.txt')
# 解压文件
with zipfile.ZipFile('archive.zip', 'r') as zipf:
zipf.extractall('extracted_files')
- 文件的遍历
使用 os.walk() 遍历目录树。
import os
for root, dirs, files in os.walk('.'):
print(root, "consumes", end=" ")
print(sum([os.path.getsize(os.path.join(root, name)) for name in files]), end=" ")
print("bytes in", len(files), "non-directory files")
标签:Chapter,PythonL,01,name,age,元素,person,numbers,print
From: https://blog.csdn.net/2403_86682230/article/details/141053844