Python学习笔记(语法篇)

本篇博客大部分内容摘自埃里克·马瑟斯所著的《Python编程:从入门到实战》(入门类书籍),采用举例的方式进行知识点提要

关于Python学习书籍推荐文章 《学习Python必备的8本书》

Python语法特点:

  1. 通过缩进进行语句组织
  2. 不需要变量或参数的声明
  3. 冒号

1 变量和简单数据结构

1.1 变量命名

只能包含字母、数字和下划线,且不能以数字打头。

1.2 字符串

在Python中,用引号括起的都是字符串,其中的引号可以是单引号或双引号

#示例1
"This is a string."
'This is also a string.'

#示例2
'I told my friend, "Python is my favorite language!"'
"The language 'Python' is named after Monty Python, not the snake."
"One of Python's strengths is its diverse and supportive community."
1.2.1 使用方法修改字符串大小写
#title()

name = "ada lovelace"
print(name.title())

Ada Lovelace  #输出

#upper(),lower()

name = "Ada Lovelace"
print(name.upper())
print(name.lower())

ADA LOVELACE  #输出
ada lovelace
1.2.2 合并(拼接)字符串
#用‘+’实现

first_name = "ada"
last_name = "lovelace"
full_name = first_name+" "+last_name
message = "Hello, "+full_name.title()+"!" 
print(message) 
1.2.3 使用 /t or /n 添加空白

在编程中,空白泛指任何非打印字符,如空格、制表符和换行符。

>>>print("Languages:\n\tPython\n\tC\n\tJavaScript")

#输出
Languages:
    Python
    C
    JavaScript
1.2.4 删除空白
>>>favorite_language = ' python ' 

>>>favorite_language.rstrip() #剔除字符串末尾的空白
' python'

>>>favorite_language.lstrip() #剔除字符串开头的空白
'python '

>>>favorite_language.strip() #剔除字符串两端的空白
'python'

1.3 数字

1.3.1 运算
>>>2+3
5
>>>3 - 2
1
>>>2 * 3
6
>>>3 / 2
1.5
>>>3 ** 2 #乘方运算
9
>>>2+3*4
14
>>>(2+3) * 4
20
1.3.2 使用函数str()避免类型错误
age = 23
message = "Happy "+str(age)+"rd Birthday!"
print(message)

#输出
Happy 23rd Birthday!

2 列表

bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)

#Python将打印列表的内部表示,包括方括号:
['trek', 'cannondale', 'redline', 'specialized']

2.1 访问列表元素

bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)

#输出
trek

通过将索引指定为-1,可让Python返回最后一个列表元素,类似地,索引-2返回倒数第二个列表元素,索引-3返回倒数第三个列表元素,以此类推。

bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[-1])  #当且仅当列表为空时,会导致错误

#输出
specialized

2.2 添加、删除列表元素

2.2.1 添加元素

方法append() --向列表末尾添加元素

motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles.append('ducati') 
print(motorcycles)

#输出
['honda', 'yamaha', 'suzuki']  
['honda', 'yamaha', 'suzuki', 'ducati']

方法insert()–在列表的任何位置添加新元素

motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati') 
print(motorcycles)

#输出
['ducati', 'honda', 'yamaha', 'suzuki']
2.2.2 删除元素

知道要删除的元素在列表中的位置时,可使用del语句

motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[0] 
print(motorcycles)

#输出
['honda', 'yamaha', 'suzuki']
['yamaha', 'suzuki']

方法pop() 可删除列表末尾的元素,并让你能够接着使用它。

motorcycles = ['honda', 'yamaha', 'suzuki'] 
print(motorcycles)
popped_motorcycle = motorcycles.pop() 
print(motorcycles) 
print(popped_motorcycle) 

#输出
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha']
suzuki

方法pop(要删除的元素的索引) 可以删除列表中任何位置的元素。

motorcycles = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycles.pop(0) 
print('The first motorcycle I owned was a '+first_owned.title()+'.') 

#输出
The first motorcycle I owned was a Honda.

方法remove()– 根据值删除元素

motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati') 
print(motorcycles)

#输出
['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']

注意 方法remove()只删除第一个指定的值

2.3 组织列表

方法sort()–对列表进行永久性排序

cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort() 
print(cars)

#输出
['audi', 'bmw', 'subaru', 'toyota']


#相反顺序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)

['toyota', 'subaru', 'bmw', 'audi']  #输出

函数sorted()–临时排序

cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:") 
print(cars)
print("\nHere is the sorted list:") 
print(sorted(cars))
print("\nHere is the original list again:") 
print(cars)

#输出
Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']
Here is the sorted list:
['audi', 'bmw', 'subaru', 'toyota']
Here is the original list again: 
['bmw', 'audi', 'toyota', 'subaru']

方法reverse()–反转列表元素的排列顺序

cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars)

#输出
['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']

函数len()–确定列表的长度

>>>cars = ['bmw', 'audi', 'toyota', 'subaru']
>>>len(cars)
4

3 操作列表

3.1 遍历列表

for循环

magicians = ['alice', 'david', 'carolina'] 
for magician in magicians: 
    print(magician) 

#输出
alice
david
carolina

3.2 创建数值列表

方法range(),Python在到达指定的第二个索引前面的元素后停止。

for value in range(1,5):
    print(value)

#输出
1  
2
3
4

even_numbers = list(range(2,11,2))  #最后一个‘2’表示步长
print(even_numbers)

#输出
[2, 4, 6, 8, 10]

利用方法range()创建数值列表的两种方式:

numbers = list(range(1,6))
print(numbers)

#输出
[2, 4, 6, 8, 10]

squares = []
for value in range(1,11):
    squares.append(value**2) 
print(squares)

#输出
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
3.2.1 对数值列表执行简单的统计计算
>>>digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>>min(digits)
0
>>>max(digits)
9
>>>sum(digits)
45
3.2.2 列表解析
squares = [value**2 for value in range(1,11)]
print(squares)

#输出
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

#value**2:用于生成要存储到列表中的值的表达式
#for循环:为表达式提供值,且for语句末尾不应有冒号

3.3 使用列表的一部分

3.3.1 切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3]) #到达指定的第二个索引前面的元素后停止

#输出也是一个列表
['charles', 'martina', 'michael']


"""没有指定起始索引,Python从列表开头开始提取"""
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[:4])

#输出
['charles', 'martina', 'michael', 'florence']


"""省略终止索引,切片终止于结尾"""
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[2:])

#输出
['michael', 'florence', 'eli']

players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[-3:])  #打印列表最后3个元素
3.3.2 遍历切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("Here are the first three players on my team:")
for player in players[:3]: 
    print(player.title())

#输出
Here are the first three players on my team:
Charles
Martina
Michael
3.3.3 复制列表
#利用
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]  #friend_foods为 my_foods的副本
my_foods.append('cannoli') 
friend_foods.append('ice cream') 
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)

#输出
My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli'] 
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'ice cream'] 举例

#举例一种行不通的方法
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods 
#新变量friend_foods关联到包含在my_foods中的列表,两个变量指向同一列表
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)

#输出
My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']

3.4 元组–不可变的列表

  • 用圆括号标识
  • 元素不可改,但可修改元组变量

4 if语句

#使用 and/or 检查多个条件
#关键词in检查特定值是否包含在列表中,关键词not in检查特定值是否不包含在列表中
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users: 
    print(user.title()+", you can post a response if you wish.")

#输出
Marie, you can post a response if you wish.

age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 5
elif age < 65: 
    price = 10
else:            #else代码块可省略
    price = 5
print("Your admission cost is $"+str(price)+".")


#在if语句中将列表名用在条件表达式中时
#Python将在列表至少包含一个元素时返回True,并在列表为空时返回False
requested_toppings = [] 
if requested_toppings: 
    for requested_topping in requested_toppings:
        print("Adding "+requested_topping+".")
    print("\nFinished making your pizza!")
else: 
    print("Are you sure you want a plain pizza?")

#输出
Are you sure you want a plain pizza?

5 字典(一系列 键-值 对)

alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])

#输出
green
5

对于较大的字典,可放在多行

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }

5.1 使用字典

5.1.1 添加键-值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x_position'] = 0 
alien_0['y_position'] = 25 
print(alien_0)

#输出
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'y_position': 25, 'x_position': 0}

注意,键—值对的排列顺序与添加顺序不同。
Python不关心键—值对的添加顺序,而只关心键和值之间的关联关系。
5.1.2 删除键-值对

利用del语句

alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points'] 
print(alien_0)

#输出
{'color': 'green', 'points': 5}
{'color': 'green'}

5.2 遍历字典

5.2.1 遍历所有的键-值对
user_0 = {
    'username': 'efermi',
    'first': 'enrico',
    'last': 'fermi',
    }
for key, value in user_0.items(): 
    print("\nKey: "+key) 
    print("Value: "+value) 

#输出
Key: last
Value: fermi
Key: first
Value: enrico
Key: username
Value: efermi
5.2.2 遍历所有键
favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }
for name in favorite_languages.keys(): 
#替换为for name in favorite_languages:,输出不变
#favorite_languages.keys()返回一个列表
    print(name.title())

#输出
Jen
Sarah
Phil
Edward
5.2.3 遍历所有值
favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }
print("The following languages have been mentioned:")
for language in favorite_languages.values():
#可用set(favorite_languages.values())剔除重复项
    print(language.title())

#输出
The following languages have been mentioned:
Python
C
Python
Ruby

5.3 嵌套

"""字典列表"""
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2] 
for alien in aliens:
    print(alien)

#输出
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}


"""在字典中存储列表"""
pizza = { 
    'crust': 'thick',
    'toppings': ['mushrooms', 'extra cheese'],
    }
print("You ordered a "+pizza['crust']+"-crust pizza "+
    "with the following toppings:")
for topping in pizza['toppings']: 
    print("\t"+topping)

#输出
You ordered a thick-crust pizza with the following toppings:
    mushrooms
    extra cheese

"""在字典中存储字典"""
users = {
    'aeinstein': {
        'first': 'albert',
        'last': 'einstein',
        'location': 'princeton',
        },
    'mcurie': {
        'first': 'marie',
        'last': 'curie',
        'location': 'paris',
        },
    }
for username, user_info in users.items(): 
    print("\nUsername: "+username) 
    full_name = user_info['first']+" "+user_info['last'] 
    location = user_info['location']
    print("\tFull name: "+full_name.title()) 
    print("\tLocation: "+location.title())

#输出
Username: aeinstein
    Full name: Albert Einstein
    Location: Princeton
Username: mcurie
    Full name: Marie Curie
    Location: Paris

6 用户输入和while循环

6.1 用户输入

"""字符串输入-input()"""
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt+= "\nWhat is your first name? "
name = input(prompt)
print("\nHello, "+name+"!")

 If you tell us who you are, we can personalize the messages you see.
What is your first name? Eric
Hello, Eric!


"""数值输入-int()"""
>>>age = input("How old are you? ")
How old are you? 21
>>>age
'21'

6.2 while循环

for循环用于针对集合中的每个元素的一个代码块,而while循环不断地运行,直到指定的条件不满足为止。

#示例1
current_number = 1
while current_number <= 5:
    print(current_number)
    current_number+= 1

#输出 
1
2
3
4
5

#示例2
prompt = "\nTell me something, and I will repeat it back to you:"
prompt+= "\nEnter 'quit' to end the program. "
active = True 
while active: 
    message = input(prompt)
    if message == 'quit': 
        active = False
    else: 
        print(message)
6.2.1 使用while循环来处理列表和字典

for循环是一种遍历列表的有效方式,但在for循环中不应修改列表,否则将导致Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环。

"""在列表之间移动元素"""
unconfirmed_users = ['alice', 'brian', 'candace'] 
confirmed_users = []
while unconfirmed_users: 
    current_user = unconfirmed_users.pop() 
    print("Verifying user: "+current_user.title())
    confirmed_users.append(current_user) 
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())

#输出
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice
The following users have been confirmed:
Candace
Brian
Alice


"""删除包含特定值的所有列表元素"""
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
    pets.remove('cat')
print(pets)

#输出
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']

7 函数

7.1 传递实参

               """位置实参"""
def describe_pet(animal_type, pet_name): 
    print("\nI have a "+animal_type+".")
    print("My "+animal_type+"'s name is "+pet_name.title()+".")
describe_pet('hamster', 'harry') 

#输出
I have a hamster.
My hamster's name is Harry.


               """关键字实参"""
def describe_pet(animal_type, pet_name):
    print("\nI have a "+animal_type+".")
    print("My "+animal_type+"'s name is "+pet_name.title()+".")
describe_pet(animal_type='hamster', pet_name='harry')

#输出
describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='harry', animal_type='hamster')


               """默认值"""
#与c++相似,使用默认值时,在形参列表先列出没有默认值的形参,而后列出有默认值的形参
def describe_pet(pet_name, animal_type='dog'):
    print("\nI have a "+animal_type+".")
    print("My "+animal_type+"'s name is "+pet_name.title()+".")
describe_pet(pet_name='willie')

#输出
I have a dog.
My dog's name is Willie.
7.1.1 在函数中修改列表

将列表传递给函数后,函数就可对其进行修改。在函数中对这个列表所做的任何修改都是永久性的。

def print_models(unprinted_designs, completed_models): 
    """
    模拟打印每个设计,直到没有未打印的设计为止
    打印每个设计后,都将其移到列表completed_models中
    """
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        # 模拟根据设计制作3D打印模型的过程
        print("Printing model: "+current_design)
        completed_models.append(current_design)
def show_completed_models(completed_models): 
    """显示打印好的所有模型"""
    print("\nThe following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)

#输出
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
7.1.2 禁止函数修改列表

可将列表的副本传递给函数

function_name(list_name[:])

7.2 传递任意数量的实参

def make_pizza(*toppings):
#形参名*toppings中的星号让Python创建一个名为toppings的空元组
#并将收到的所有值都封装到这个元组中
    """概述要制作的比萨"""
    print("\nMaking a pizza with the following toppings:")
    for topping in toppings:
        print("- "+topping)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

#输出
Making a pizza with the following toppings:
- pepperoni
Making a pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese

7.3 使用任意数量的关键字实参

#形参**user_info中的两个星号让Python创建一个名为user_info的空字典
#并将收到的所有名称—值对都封装到这个字典中
def build_profile(first, last, **user_info):
    """创建一个字典,其中包含我们知道的有关用户的一切"""
    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'}

7.4 将函数存储在模块中

               """"导入整个模块"""
#pizza.py
def make_pizza(size, *toppings):
    """概述要制作的比萨"""
    print("\nMaking a "+str(size)+
          "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- "+topping)
        
#making_pizzas.py
import pizza  #pizza.py中的所有函数将被复制到这个程序中
pizza.make_pizza(16, 'pepperoni') 
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

#输出
Making a 16-inch pizza with the following toppings:
- pepperoni
Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese


               """"导入特定函数"""
from module_name import function_0, function_1, function_2

#as
import pizza as p
from pizza import make_pizza as mp


               """"导入模块中的所有函数"""
from module_name import *

8 类

8.1 创建和使用类

8.1.1 创建类
class Dog(): 
#约定Python中,首字母大写的名称指的是类
    def __init__(self, name, age): 
        """初始化属性name和age"""
        self.name = name 
        self.age = age
    def sit(self): 
        print(self.name.title()+" is now sitting.")
    def roll_over(self):
        print(self.name.title()+" rolled over!")
#类中的函数称为方法
8.1.2 给属性指定默认值
class Car():
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0   #默认值
    def get_descriptive_name(self):
        --snip--
    def read_odometer(self): 
        print("This car has "+str(self.odometer_reading)+" miles on it.")
my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()

#输出
2016 Audi A4
This car has 0 miles on it.
8.1.3 修改属性的值
                """直接修改属性的值"""
class Car():
    --snip--
my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())
my_new_car.odometer_reading = 23 
my_new_car.read_odometer()

#输出
2016 Audi A4
This car has 23 miles on it.


                """通过方法修改属性的值"""
class Car():
    --snip--
    def update_odometer(self, mileage): 
        """将里程表读数设置为指定的值"""
        self.odometer_reading = mileage
my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())
my_new_car.update_odometer(23) 
my_new_car.read_odometer()

#输出
2016 Audi A4
This car has 23 miles on it.

8.2 继承

class Car(): 
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0
    def get_descriptive_name(self):
        long_name = str(self.year)+' '+self.make+' '+self.model
        return long_name.title()
    def read_odometer(self):
        print("This car has "+str(self.odometer_reading)+" miles on it.")
    def update_odometer(self, mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")
    def increment_odometer(self, miles):
        self.odometer_reading+= miles
        
class ElectricCar(Car):
    """Represent aspects of a car, specific to electric vehicles."""
    def __init__(self, make, model, year):
        """
        电动汽车的独特之处
        初始化父类的属性,再初始化电动汽车特有的属性
        """
        super().__init__(make, model, year)
        self.battery_size = 70 
   def describe_battery(self): 
        print("This car has a "+str(self.battery_size)+"-kWh battery.")
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()

#输出
2016 Tesla Model S
This car has a 70-kWh battery.
8.2.1 将实例用作属性
class Car():
    --snip--
class Battery(): 
    def __init__(self, battery_size=70): 
        self.battery_size = battery_size
    def describe_battery(self):
        print("This car has a "+str(self.battery_size)+"-kWh battery.")

class ElectricCar(Car):
    def __init__(self, make, model, year)
        super().__init__(make, model, year)
        self.battery = Battery() #将实例用作属性

my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()

#输出
2016 Tesla Model S
This car has a 70-kWh battery.

8.3 导入类

           """导入单个类"""
from 文件名(无后缀'.py') import 类名
           """导入多个类"""
from 文件名(无后缀'.py') import 类名,类名
           """导入整个模块"""
import 文件名(无后缀'.py')
        """导入模块中的所有类"""
from 文件名(无后缀'.py') import *   (不提倡)

掌握导入函数和类的各种方法后,即可使用Python标准库(一组模块)中的任何函数和类,达到事半功倍的效果。
要了解Python标准库,有一个不错的网站 Python Module of the Week

9 文件和异常

9.1 文件的打开

文件打开模式 描述
‘r’ 只读,默认值,文件不存在则报错
‘w’ 覆盖写,文件不存在则创建
‘x’ 创建写,创建文件写,文件已存在则报错
‘a’ 追加写,文件不存在则创建
‘b’ 二进制文件模式
‘t’ 文本文件模式
‘+’ 与 r/w/x/a 一同使用,在原功能基础上增加同时读写功能,另:'r+'与’w+’功能类似,可读,覆盖写,但文件不存在时将报错

<文件名> = open(文件路径/文件名,<打开模式>)
’rb’,为文件默认打开模式。

file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt'
with open(file_path) as file_object:

#绝对文件路径示例,Windows系统使用反斜杠‘\’
#反斜杠在Python中被视为转义标记,为确保万无一失,可采用以下形式:

file_path = r'C:\Users\ehmatthes\other_files\text_files\filename.txt'

file_path = 'C:\\Users\\ehmatthes\\other_files\\text_files\\filename.txt'

9.2 从文件中读取数据

操作方法 描述
f.read(size) 参数省略,读入全部内容;给出参数,读入前size长度
f.readline(size) 参数省略,读入一行内容;给出参数,读入该行前size长度
f.readlines(hint) 参数省略,读入文件所有行,以每行为元素形成列表;给出参数,读入前hint行
9.2.1 读取整个文件
#pi_digits.txt
3.1415926535
  8979323846
  2643383279

#file_reader.py
with open('pi_digits.txt') as file_object:
#关键词 with在不再需要访问文件后将其关闭,且open()返回的文件对象只在with代码块内可用
    contents = file_object.read()
    print(contents)

#输出
3.1415926535
  8979323846
  2643383279
   
#read()到达文件末尾时返回一个空字符串,要删除可在print语句中使用rstrip()
9.2.2 文件的逐行操作
              """逐行读取,逐行处理"""
filename = 'pi_digits.txt' 
with open(filename) as file_object: 
    for line in file_object: 
        print(line)

#输出会产生更多空行:每行末尾都有一个看不见的换行符,print语句也会加上一个换行符。
#为消去多余的空白行,仍可在print语句中使用rstrip()


            """一次读入,分行处理"""
filename = 'pi_digits.txt'
with open(filename) as file_object:
    lines = file_object.readlines()  
    #将读取结果存入lines,以便在with代码块外使用
for line in lines: 
    print(line.rstrip())

#输出内容与文件内容完全一致

9.3 写入文件

操作方法 描述
f.write(s) 向文件写入一个字符串或字节流,它不会在写入的文本末尾添加换行符
f.writelines(s) 将一个元素全为字符串的列表写入文件
f.seek(offset) 改变当前文件操作指针的位置,参数含义:0-文件开头,1-当前位置,2-文件结尾

注意:Python只能将字符串写入文本文件。要将数值数据存储到文本文件中,必须先使用函数str()将其转换为字符串格式。

filename = 'pi_digits.txt'
ls=['中国','法国','美国']
with open(filename,'w+') as file_object:
    file_object.writelines(ls)
    file_object.seek(0)
    for line in file_object:
        print line

#输出
中国法国美国

9.4 异常

异常:Python创建的特殊对象,用于管理程序运行是出现的错误。

若未对异常进行处理,程序将停止,显示有关异常的报告;若编写了处理异常的代码,程序将继续运行。

try:
     Normal execution block
except A:
     Exception A handle/pass
except B:
     Exception B handle/pass
except:
     Other exception handle/pass
else:
     if no exception,get here
finally:
     print("finally")
#pass让Python什么都不要做

try:可能产生异常的语句
except 捕获并处理异常,通常异常有不同类型,可分别处理
else:try语句块正常执行时,无异常产生,执行else语句块
finally:无论是否有异常产生,均执行

#示例1
try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")

#输出
You can't divide by zero!


#示例2
def count_words(filename):
    """计算一个文件大致包含多少个单词""" 
    try:
        with open(filename) as f_obj:
            contents = f_obj.read()
    except FileNotFoundError:
        msg = "Sorry, the file "+filename+" does not exist."
        print(msg)
    else:
        # 计算文件大致包含多少个单词
        words = contents.split()
        #方法split()以空格为分隔符将字符串分拆成多个部分,并将这些部分都存储到一个列表中。
        num_words = len(words)
        print("The file "+filename+" has about "+str(num_words)+
            " words.")
filename = 'alice.txt'
count_words(filename)

9.5 存储数据

模块json:能保存用户数据,以免在程序停止运行后丢失。模块json可将简单的Python数据结构转储到文件中,并在程序再次运行时加载该文件中的数据。

9.5.1 使用json.dump()和json.load()
#number_writer.py
import json  
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json' #注意这里的文件拓展名 
with open(filename, 'w') as f_obj: 
    json.dump(numbers, f_obj) 
    #json.dump()的两个实参分别是要存储的数据以及可用于存储数据的文件对象

#number_reader.py
import json
filename = 'numbers.json' 
with open(filename) as f_obj: 
    numbers = json.load(f_obj) 
print(numbers)

#输出
[2, 3, 5, 7, 11, 13]

#以上演示表明这是一种在程序之间共享数据的简单方式

10 测试代码

10.1 测试函数

#name_function.py
def get_formatted_name(first, last, middle=''):
    if middle:
        full_name = first+' '+middle+' '+last
    else:
        full_name = first+' '+last
    return full_name.title()

#test_name_function.py
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
#这个类必须继承unittest.TestCase类
    def test_first_last_name(self):
    #方法名必须以test_打头,这样才会在运行该程序时自动运行
        formatted_name = get_formatted_name('janis', 'joplin')
        self.assertEqual(formatted_name, 'Janis Joplin')
        #断言方法assertEqual()用以核实得到的结果是否与期望的结果一致
    def test_first_last_middle_name(self):        
        formatted_name = get_formatted_name( 'wolfgang', 'mozart', 'amadeus')
        self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart')
if __name__=="__main__":
     unittest.main()

#输出
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK

运行测试用例时,每完成一个单元测试,Python都打印一个字符:测试通过时打印一个句点;测试引发错误时打印一个E;测试导致断言失败时打印一个F。

10.2 测试类

10.2.1 各种断言方法
方法 用途
assertEqual(a,b) 核实a==b
assertNotEqual(a,b) 核实a!=b
assertTrue(x) 核实x为True
assertFalse(x) 核实x为False
assertIn(item,list) 核实item在list中
assertNotIn(item,list) 核实item不在list中
10.2.2 测试示例
#survey.py
class AnonymousSurvey():
    """收集匿名调查问卷的答案"""
    def __init__(self, question): 
        """存储一个问题,并为存储答案做准备"""
        self.question = question
        self.responses = []
    def show_question(self): 
        """显示调查问卷"""
        print(self.question)
    def store_response(self, new_response): 
        """存储单份调查答卷"""
        self.responses.append(new_response)
    def show_results(self): 
        """显示收集到的所有答卷"""
        print("Survey results:")
        for response in self.responses:
            print('- '+response)

#test_survey.py
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
    def test_store_single_response(self):
        question = "What language did you first learn to speak?"
        my_survey = AnonymousSurvey(question) 
        my_survey.store_response('English')
        self.assertIn('English', my_survey.responses) 
    def test_store_three_responses(self):
        question = "What language did you first learn to speak?"
        my_survey = AnonymousSurvey(question)
        responses = ['English', 'Spanish', 'Mandarin'] 
        for response in responses:
            my_survey.store_response(response)
        for response in responses: 
            self.assertIn(response, my_survey.responses)
if __name__=="__main__":
     unittest.main()

#输出
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
10.2.3 方法setUp()
#test2_survey.py
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
    def setUp(self):
        question = "What language did you first learn to speak?"
        self.my_survey = AnonymousSurvey(question) 
        self.responses = ['English', 'Spanish', 'Mandarin'] 
        #Python将先运行方法setUp(),再运行各个以test_打头的方法。
    def test_store_single_response(self):
        self.my_survey.store_response(self.responses[0])
        self.assertIn(self.responses[0], self.my_survey.responses)
    def test_store_three_responses(self):
        for response in self.responses:
            self.my_survey.store_response(response)
        for response in self.responses:
            self.assertIn(response, self.my_survey.responses)
if __name__=="__main__":
     unittest.main()
发布了25 篇原创文章 · 获赞 46 · 访问量 6553
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览