Python 文件操作
文件操作的重要性
在编程中,我们经常需要读取文件中的数据或将数据写入文件。Python 提供了内置的函数来轻松处理文件操作。
打开文件
使用 open()
函数打开文件。它需要两个参数:文件名和模式。
常用的模式有:
'r'
: 读取 (默认模式)'w'
: 写入 (如果文件存在则覆盖,不存在则创建)'a'
: 追加 (如果文件存在则在末尾追加,不存在则创建)'x'
: 创建 (如果文件已存在则失败)'+'
: 更新 (读写)'b'
: 二进制模式't'
: 文本模式 (默认)
# 打开文件进行读取
try:
file = open("example.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("文件未找到!")
finally:
if 'file' in locals() and not file.closed:
file.close() # 始终关闭文件
使用 with
语句
with
语句可以确保文件在使用完毕后自动关闭,即使发生错误也是如此。这是推荐的文件操作方式。
try:
with open("example.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("文件 'example.txt' 未找到!")
# 写入文件
with open("output.txt", "w") as file:
file.write("这是第一行。\n")
file.write("这是第二行。\n")
# 追加到文件
with open("output.txt", "a") as file:
file.write("这是追加的一行。\n")
读取文件内容
有多种方法可以读取文件内容:
Python 面向对象编程 (OOP)
什么是面向对象编程?
面向对象编程 (Object-Oriented Programming, OOP) 是一种编程范式,它使用“对象”来设计软件。对象可以包含数据(属性)和代码(方法)。
Python 是一种完全支持面向对象编程的语言。
类 (Class) 和对象 (Object)
- 类 (Class): 创建对象的蓝图或模板。它定义了对象的属性和方法。
- 对象 (Object): 类的实例。
class Dog:
# 类属性
species = "Canis familiaris"
# 初始化方法 (构造函数)
def __init__(self, name, age):
# 实例属性
self.name = name
self.age = age
# 实例方法
def description(self):
return f"{self.name} is {self.age} years old"
def speak(self, sound):
return f"{self.name} says {sound}"
# 创建 Dog 类的实例 (对象)
my_dog = Dog("Buddy", 3)
# 访问实例属性
print(my_dog.name) # 输出: Buddy
print(my_dog.age) # 输出: 3
# 调用实例方法
print(my_dog.description()) # 输出: Buddy is 3 years old
print(my_dog.speak("Woof Woof")) # 输出: Buddy says Woof Woof
# 访问类属性
print(my_dog.species) # 输出: Canis familiaris
OOP 的主要原则
- 封装 (Encapsulation): 将数据(属性)和操作数据的方法(方法)捆绑在一起,并对外部隐藏对象的内部状态。
- 继承 (Inheritance): 允许我们定义一个继承另一个类的所有方法和属性的类。父类(基类)和子类(派生类)。
- 多态 (Polymorphism): 允许我们以统一的方式处理不同类的对象。通常意味着子类可以覆盖父类的方法。
继承示例
class Bulldog(Dog): # Bulldog 继承自 Dog
def speak(self, sound="Gruff Gruff"): # 重写父类的方法 (多态)
return f"{self.name} says {sound} with a bulldog accent!"
my_bulldog = Bulldog("Rocky", 5)
print(my_bulldog.description()) # 调用继承自 Dog 类的方法
print(my_bulldog.speak()) # 调用 Bulldog 类重写的方法
面向对象编程可以帮助我们编写更模块化、可重用和易于维护的代码。
Python 函数详解
什么是函数?
函数是一段组织起来的、可重复使用的、用来实现单一或相关联功能的代码段。函数能提高应用的模块性和代码的重复利用率。
定义函数
在 Python 中,使用 def
关键字来定义函数。
def greet(name):
"""这是一个简单的问候函数"""
print(f"Hello, {name}!")
# 调用函数
greet("Cline") # 输出: Hello, Cline!
函数参数
函数可以接受参数,参数是传递给函数的值。
- 位置参数: 按照参数定义的顺序传递。
- 关键字参数: 通过参数名指定,顺序无关紧要。
- 默认参数: 如果调用函数时没有提供参数值,则使用默认值。
- 可变参数:
*args
: 接收任意数量的位置参数,打包成一个元组。**kwargs
: 接收任意数量的关键字参数,打包成一个字典。
def describe_pet(animal_type, pet_name="Doggy"): # 默认参数
print(f"I have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet("hamster", "Harry") # 位置参数
describe_pet(pet_name="Willy", animal_type="whale") # 关键字参数
describe_pet("cat") # 使用默认参数
def make_pizza(*toppings): # *args
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
def build_profile(first, last, **user_info): # **kwargs
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('albert', 'einstein',
location='princeton',
field='physics')
print(user_profile)
# 输出: {'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}
返回值
函数可以使用 return
语句返回一个值。如果函数没有 return
语句,它默认返回 None
。