【入门书籍】Python 编程-从入门到实践【上】,Python会尽力找


Chapter_2_变量和简单数据类型


# In[1]
# 2.3 字符串
name = "ada loveada"
print(name.title())
print(name.upper())
print(name.isupper())
name = name.upper()
print(name.isupper())
print(name.lower())
print(name.swapcase()) # 大写变小写,小写变大写

# 合并字符串 1
first_name = 'ada'
last_name = 'lovelace'
full_name = first_name + " " + last_name
print(full_name)
# 合并字符串 2
print("Hello," + full_name.title() + "!")

# 使用制表符或换行符来添加空白
print("\tpython")

'''删除空白----------要确保字符串末尾没有空白,可使用方法'''
favorite_language = "python "
print(len(favorite_language))
print(len(favorite_language.rstrip()))
# 要永久删除这个字符串中的空白,必须将删除操作的结果存回到变量中
favorite_language = favorite_language.rstrip()
# favorite_language = favorite_language.replace(" ","")
print(favorite_language)
print(favorite_language.rstrip("python"))
print('Monty Python'.rstrip(' Python'))

# 2.3.5 使用字符串时避免语法错误

# In[2]
# 2.4 数字
# 2.4.1 整数
# 2.4.2 浮点数
'''
所有语言都存在这种问题,没有什么可担心的。Python会尽力找到一种方式,以尽可能精确
地表示结果,但鉴于计算机内部表示数字的方式,这在有些情况下很难。就现在而言,暂时忽略
多余的小数位数即可;在第二部分的项目中,你将学习在需要时处理多余小数位的方式。
'''

Chapter_3_列表简介

# In[1]
""" 3.1 列表是什么? """
bicycles = ['tiek', 'cannondale', 'redline', 'specialized']
print(bicycles[0].title())
print(bicycles[-1])

""" 3.2 修改、添加和删除元素 """
'''3.2.1 修改列表元素'''
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles[0])
motorcycles[0] = 'ducati'
print(motorcycles[0])

'''3.2.2 在列表中添加元素'''
motorcycles.append("asdad")
print(motorcycles)
motorcycles.insert(0, 'asdasdasd') # 方法insert()在索引0处添加空间,并将值'asdasdasd'存储到这个地方。
print(motorcycles)
'''3.2.3 从列表中删除元素'''
# 使用 del
del motorcycles[0]
print(motorcycles)
# 使用方法pop()删除元素,并接着使用它的值
motorcycles = ['honda', 'yamaha', 'suzuki']
poped_motorcycles = motorcycles.pop(0)
print(motorcycles)
print(poped_motorcycles)
# 总结:如果你要从列表中删除一个元素,且不再以任何方式使用它,就使用del语句;如果你要在删除元素后还能继续使用它,就使用方法pop()。
'''4. 根据值删除元素'''
motorcycles = ['honda', 'honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles.remove('honda') # 方法remove()只删除第一个指定的值
print(motorcycles)

''' 3.3 组织列表 '''
motorcycles = ['honda', 'yamaha', 'suzuki']
test_Sort = ['12', 'asd', '12.3', '123']
'''3.3.1 使用方法 sort()对列表进行永久性排序'''
motorcycles.sort()
print(motorcycles)
test_Sort = ['12', 'asd', '12.3', '123']
test_Sort.sort() # 永久性地修改了列表元素的排列顺序
print(test_Sort) # ['12', '12.3', '123', 'asd']
str_ = 'asdASDgh'
test_Sort.reverse()
str_ = str_.swapcase()
print(str_)
print(test_Sort)
'''3.3.2 使用函数 sorted()对列表进行临时排序'''
motorcycles = ['honda', 'Yamaha', 'yam', 'suzuki']
print(sorted(motorcycles))
print(motorcycles)
print(sorted(motorcycles, reverse=True))
print(motorcycles)

# In[2]
# 倒置字符串1
str_ = 'abcdefghijklmn'
list_str = []
for i in str_:
list_str.append(i)
list_str.reverse()
str_reverse = ''
for i in list_str:
str_reverse += i
print(str_reverse)

# 倒置字符串2
print(str_[::])
print(str_[::-1])

# 倒置字符串3
result = ''
for i in range(len(str_) - 1, -1, -1):
result += str_[i]
print(result)

# In[2]
list_1 = {'string': '1', 'string2': 2}
list_2 = list_1
list_2.update({'string3': '3'})
print(list_1)
print(list_2)

'''
my_foods = ['pizza', 'falafel', 'carrot cake']
#friend_foods = my_foods[:]
# VS
friend_foods = my_foods # 并非把副本存储到 friend_foods
my_foods.append('cannoli')
friend_foods.append('123')
print(friend_foods)
print(my_foods)
'''

Chapter_4_操作列表

# In[1]
magicians = ['alice', 'david', 'carolina']
for i in magicians:
print(i)
'''4.1.1 深入地研究循环'''
a = list(range(1, 10, 2))
print(a)
print(sum(a))

'''----------4.3.4 列表解析----------- '''
# value = list(range[0,11,2])
squares = [value ** 2 for value in range(1, 11)]
print(squares)

# 作业2 计算 1~1 000 000 的总和
numbers = list(range(1, 1000001))
sumNum = 0
for i in numbers:
sumNum += i
result = sum(numbers)
print(type(numbers))
print(result, sumNum)

''' 4.4 使用列表的一部分 --=-=-=-=-=- 切片 '''
# 你可以生成列表的任何子集,例如,如果你要提取列表的第2~4个元素,可将起始索引指定为 1,并将终止索引指定为 4:
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[1:4])
print(players[2:])
print(players[:2])
print(players[-3:]) # 倒数第三个到最后

''' P75 4.4.2 遍历切片'''
players = ['charles', 'martina', 'michael', 'florence', 'eli']
for i in players[:3]:
print(i)

''' 4.4.3 复制列表 '''
my_foods = ['pizza', 'falafel', 'carrot cake']
# friend_foods = my_foods[:]
# VS
friend_foods = my_foods # 并非把副本存储到 friend_foods
my_foods.append('cannoli')
print(friend_foods)

'''
列表总结:
列表非常适合用于存储在程序运行期间可能变化的数据集。列表是可以修改的,这对处理网
站的用户列表或游戏中的角色列表至关重要。
'''
# In[2]
"""========4.5 元组========="""
# 不可变的列表被称为元组
''' 4.5.1 定义元组 '''
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
# dimensions[0] = 250 # TypeError: 'tuple' object does not support item assignment

''' 4.5.3 修改元组变量 '''
dimensions = (200, 50)
dimensions = (20, 20, "123", 10)
print(dimensions)

Chapter_5_if语句

# In[1] 5.2.2 检查是否相等时不考虑大小写
var = 'Audi'
print(var.lower() == 'audi')
print(var) # 函数 lower() 不会修改存储在变量car中的值

# In[2] 5.2.3 检查是否不相等 5.2.4 比较数字 5.2.5 检查多个条件
age_1 = 10
age_2 = 12
if age_1 > 10 and age_2 > 10:
print('都大于10岁')
else:
if age_1 >= 10:
print('age_1 大于等于10')
if age_2 >= 10:
print('age_2 大于等于10')

# In[3] 5.2.6 检查特定值是否包含在列表中 5.2.7 检查特定值是否不包含在列表中
requested_toppings = ['mushrooms', 'onions', 'pineapple']
print('onions' in requested_toppings)
print('onions' not in requested_toppings)

# In[3] 5.2.8 布尔表达式 5.3.3 if-elif-else 结构
age = int(input('请输入你的年龄查询票价:'))
if age <= 0:
print("别闹,你不是人!")
elif age < 7:
print("你还小,不需要钱")
elif age <= 18:
print("你还是学生,只要 5 元")
else:
print('你不小了,成人票:58元')

Chapter_6_字典

# In[1] 6.2.2 添加键—值对
'''
字典是一种动态结构,可随时在其中添加键—值对。要添加键—值对,可依次指定字典名、用
方括号括起的键和相关联的值。
'''
alien = {'color': 'green', 'points': 5}
print(alien)
alien['x_pos'] = 10 # 添加
print(alien)
alien['y_pos'] = 12
print(alien)
alien['color'] = 'red'
print(alien)

# In[2]
alien = {}
print(type(alien))

# In[3]
alien = {'color': 'green', 'points': 5}
print(alien['color'])
del alien['color']
print(alien)

# In[4] 6.2.6 由类似对象组成的字典
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}

# In[5] 6.3 遍历字典 多种遍历字典的方式:可遍历字典的所有键—值对、键或值。
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
print(str(user_0.items()))
# np.savetxt("dict.txt",str(a),fmt='%s')
for key, value in user_0.items():
print("\nKey:", key)
print("Value:", value)
'''注意,即便遍历字典时,键—值对的返回顺序也与存储顺序不同。Python不关心键—值对的存储顺序,而只跟踪键和值之间的关联关系。'''

# In[6] 6.3.2 遍历字典中的所有键
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for key in favorite_languages.keys():
print(key.title())
# 等价于 || 以下的语句 显式与隐式功能相同
for key in favorite_languages:
print(key.title())

# In[7] 6.3.3 按顺序遍历字典中的所有键
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in sorted(favorite_languages.keys()): # 临时排序而已
print(name.title())
print(favorite_languages.keys())

# In[8] 6.3.4 遍历字典中的所有值
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for value in favorite_languages.values():
print(value.title())
print('------以上方法这种做法提取字典中所有的值,而没有考虑是否重复------')
# 以上方法这种做法提取字典中所有的值,而没有考虑是否重复
for value in set(favorite_languages.values()):
print(value.title())

# In[9]
# '''6.4 嵌套 可以在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典'''
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'red', 'points': 10}
alien_2 = {'color': 'blue', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for al in aliens:
print(al)

print("----改进变高级一点----")

# 改进变高级一点
aliens = []
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5}
aliens.append(new_alien)
for alien in aliens[:5]:
print(alien)

# In[10]
# 例如,你如何描述顾客点的比萨呢?如果使用列表,只能存储要添加的比萨配料;但如果使用字典,就不仅可在其中包含配料列表,还可包含其他有关比萨的描述。
"""P114 6.4.2 在字典中存储列表"""
""" 嵌套 """

Chapter_7_用户输入和 while 循环

第七章 用户输入和 while 循环
7.1 函数 input() 的工作原理
7.1.1 编写清晰的程序
message = input("请输入你的名字:")
print(f"你好!{message}!")
请输入你的名字:一叶知秋
你好!一叶知秋!
7.1.2 使用 int() 来获取数值输入
age = input("请输入你的年龄:")
age = int(age)
if age >=18:
print("你已经成年了!")
elif age <18:
print("你还未成年!")
请输入你的年龄:18
你已经成年了!
7.1.3 求模运算符
例如:求模运算可以判断 x 是否是奇数、偶数
x = input('请你输入一个整数:')
try:
x = int(x)
if x % 2 == 0:
print("偶数!")
else:
print("奇数!")
except:
print("你输入的不是整数!")
请你输入一个整数:20
偶数!
7.2 while 循环简介
7.2.1 使用while循环
7.2.2 让用户选择何时退出
7.2.3 使用标志
active = True
while active:
message = input("输入“退出”即可退出while!")
if message == '退出':
active = False
print('退出成功!')
else:
print(f"{message}")
输入“退出”即可退出while!不退出
不退出
输入“退出”即可退出while!退出
退出成功!
7.2.4 使用 break 退出循环
7.2.5 在循环中使用 continue
7.2.6 避免无限循环
7.3 使用while循环来处理列表和字典
为什么使用while而不是for,优点如下:
比如 for 循环列表很优秀,但是for 循环时候不应该修改列表
要在遍历列表的同时修改列表,可以使用 while
7.3.1 在列表之间移动元素
假设有一个列表,其中包含新注册但还未验证的网站用户;

问:验证这些用户后,如何将他们移到另一个已验证用户列表中呢?

答:一种办法是使用一个while循环,在验证用户的同时将其从未验证用户列表中提取出来, 再将其加入到另一个已验证用户列表中。

代码可能类似于下面这样:

unconfirmed_users = ['alice','brian']
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print(f"{current_user}的验证过程,通过!")
confirmed_users.append(current_user)
print("验证通过的人名:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
brian的验证过程,通过!
alice的验证过程,通过!
验证通过的人名:
Brian
Alice
max(list(map(int,input("输入一系列整数:").split(" "))))
输入一系列整数:12
12

Chapter_8_函数

In [1]:
def greet_user():
    """显示简单的问候语"""
    print("hello")
In [2]:
greet_user()
 
hello
In [3]:
def greet_user(username):
    print(f"hello{username}")
In [4]:
greet_user("一叶知秋")
 
hello一叶知秋
 

8.4 传递列表

 

8.4.1 在函数中修改列表

In [6]:
# 传递列表
def greet_user(names):
    """向列表中的每一个用户都发出简单的问候"""
    for i in names:
        msg = "hello," + i.title() + "!"
        print(msg)
In [7]:
usernames = ["han","joy","davin"]
In [8]:
greet_user(usernames)
 
hello,Han!
hello,Joy!
hello,Davin!
In [9]:
# 修改列表
def print_models(unprinted_designs, completed_models):
    """模拟打印每一个设计,直到没有未打印的设计为止,打印每个设计后,都将其移动到completed_models"""
    while unprinted_designs:
        current_model = unprinted_designs.pop()
    <span class="nb">print<span class="p">(<span class="s2">"打印模型:"<span class="o">+ <span class="n">current_model<span class="p">)
    <span class="n">completed_models<span class="o">.<span class="n">append<span class="p">(<span class="n">current_model<span class="p">)

def show_completed_models(completed_models):
"""显示打印好的所有模型"""
print("这些模型已经打印:")
for model in completed_models:
print(model)

In [10]:
unprinted_designs = ['iphone case','robot pendant','dodecahedron']
completed_models = []
In [11]:
print_models(unprinted_designs,completed_models)
 
打印模型:dodecahedron
打印模型:robot pendant
打印模型:iphone case
In [14]:
show_completed_models(completed_models)
print(unprinted_designs)
print(completed_models)
 
这些模型已经打印:
dodecahedron
robot pendant
iphone case
[]
['dodecahedron', 'robot pendant', 'iphone case']
In [28]:
# 函数传参 传入的列表会使得原先的列表发生改变 所以传递的是列表地址?
# 如果是一些其他类型的呢?
str_ = "str"
tuple_ = (1,2,1,1,1)
list_ = ['1','2']
dict_ = {1:"一",2:"二"}
set_ = {1,2,3,4}
int_ = 10
float_ = 1.1
def is_changed(variable):
    variable += (["哈哈哈"],)
    print(variable)  
In [29]:
is_changed(tuple_)
tuple_
 
(1, 2, 1, 1, 1, ['哈哈哈'])
Out[29]:
(1, 2, 1, 1, 1)
In [30]:   In [32]:    
a
['1', '2']
b
c
In [34]:    
制作一款10英寸披萨,配料有:('土豆', '芝士', '沙拉酱')
In [40]:   Out[40]:
{'firstname': '一叶',
 'lastname': '知秋',
 'loc': '博客园',
 'Email': 'ye.qiu.work@outlook.com'}
In [51]:
# 练习8-9 魔术师
"""
创建一个包含魔术师名字的列表,并将其传递给一个名为
show_magicians()的函数,这个函数打印列表中每个魔术师的名字。
"""
magician_names = ['a','b','h']
def show_magicians(names):
    for name in names:
        print(name)
show_magicians(magician_names)
 
a
b
h
In [50]:
# 8-10 了不起的魔术师
"""在你为完成练习 8-9 而编写的程序中,编写一个名为
make_great()的函数,对魔术师列表进行修改,在每个魔术师的名字中都加
入字样“the Great”。调用函数 show_magicians(),确认魔术师列表确实
变了。
"""
# 已修改
def make_great(names):
    for index,name in enumerate(names):
        name = "the Great " + name
        names[index] = name
magician_names = ['a','b','h']
def show_magicians(names):
    make_great(names)
    for name in names:
        print(name)
show_magicians(magician_names)
 
the Great a
the Great b
the Great h
In [60]:
# 8-11 不变的魔术师:
"""
修改你为完成练习 8-10 而编写的程序,在调用函数
make_great()时,向它传递魔术师列表的副本。由于不想修改原始列表,请
返回修改后的列表,并将其存储到另一个列表中。分别使用这两个列表来调
用 show_magicians(),确认一个列表包含的是原来的魔术师名字,而另一个
列表包含的是添加了字样“the Great”的魔术师名字。
"""
# 已修改

magician_origin_names = ['a','b','h']
magician_current_names = []

def make_great(names):
for index,name in enumerate(names):
name = "the Great " + name
names[index] = name
return names

magician_current_names = make_great(magician_origin_names[:])
def show_magicians(names):
for name in names:
print(name)

show_magicians(magician_origin_names)
show_magicians(magician_current_names)

 
a
b
h
the Great a
the Great b
the Great h
In [61]:
# 当实参不止一个的时候,可以使用 * 号进行处理
# 例如:
def make_pizza(*toppings):
    for i in toppings:
        print(i)
In [62]:
make_pizza("a",['1','2'],"b","c")
 
a
['1', '2']
b
c
In [63]:
# 位置实参! 和 任意数量实参
# 形参名字*toppings中的*让Python创建了一个名为toppings的空元组,并将所有接受过来的值封装在这个元组里
# 让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后
def make_pizza(size,*toppings):
    print(f"制作一款{size}英寸披萨,配料有:{toppings}")

make_pizza(10,"土豆","芝士","沙拉酱")

 
制作一款10英寸披萨,配料有:('土豆', '芝士', '沙拉酱')
In [81]:
# 学习完 一个星号*,再学习 两个星号*的使用方法
def build_profile(first,last,**userInfo):
    print(userInfo)
    profile = {}
    profile["firstname"] = first
    profile["lastname"] = last
    for key,value in userInfo.items():
        profile[key] = value
    return profile

# build_profile("一叶","知秋",loc = "博客园",Email = "ye.qiu.work@outlook.com")build_profile("一叶","知秋",loc = "博客园",Email = "ye.qiu.work@outlook.com")

build_profile("一叶","知秋",Email = "ye.qiu.work@outlook.com")

 
{'Email': 'ye.qiu.work@outlook.com'}
Out[81]:
{'firstname': '一叶', 'lastname': '知秋', 'Email': 'ye.qiu.work@outlook.com'}
 

8.6 将函数存储在模块中

 

8.6.1 导入整个模块

 

8.6.2 导入特定的函数

 

8.6.3 使用 as 给函数指定别名

 

8.6.4 使用 as 给模块指定别名

 

8.6.5 导入模块中的所有函数

 

8.7 函数编写指南

 

8.8 小结

Chapter_9_类

class Dog():
def __init__(self, name, age):
self.name = name
self.age = age

def sit(self):
return ("坐下")

def roll_over(self):
print("打滚")


my_dog = Dog("一叶知秋", 6)
print(f"我的狗的名字:{my_dog.name},年龄:{my_dog.age},技能:{my_dog.sit()}")

your_dog = Dog("猪八戒",4)

# 动手试一试:
"""
9-1 餐馆:创建一个名为 Restaurant 的类,其方法__init__()设置两个属性:
restaurant_name 和 cuisine_type。创建一个名为 describe_restaurant()的方法和一个
名为 open_restaurant()的方法,其中前者打印前述两项信息,而后者打印一条消息,
指出餐馆正在营业。
根据这个类创建一个名为 restaurant 的实例,分别打印其两个属性,再调用前述
两个方法。
9-2 三家餐馆:根据你为完成练习 9-1 而编写的类创建三个实例,并对每个实例调
用方法 describe_restaurant()。
9-3 用户:创建一个名为 User 的类,其中包含属性 first_name 和 last_name,还有
用户简介通常会存储的其他几个属性。在类 User 中定义一个名为 describe_user()的方
法,它打印用户信息摘要;再定义一个名为 greet_user()的方法,它向用户发出个性化
的问候。
创建多个表示不同用户的实例,并对每个实例都调用上述两个方法。
"""
class Car():
"""一次模拟汽车的简单尝试"""

def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0

def fill_gas_tank(self):
print("所有汽车都烧油!")

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("不可以回调里程数!")

def increment_odometer(self, miles):
self.odometer_reading += miles

class Battery():
def __init__(self,battery_size=70):
self.battery_size = battery_size

def describe_battery(self):
print(f"该车电池尺寸为:{self.battery_size}")

def get_range(self):
"""打印一条消息,指出电瓶的续航里程"""
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270

message = "This car can go approximately " + str(range)
message += " miles on a full charge."
print(message)

class ElectricCar(Car):
"""电动车的独特之处"""

def __init__(self, make, model, year):
super().__init__(make, model, year)
self.battery = Battery()

def fill_gas_tank(self):
print("我是电车不烧油!")


my_tesla = ElectricCar("特斯拉", "models", 2016)
my_tesla.increment_odometer(10)
my_tesla.fill_gas_tank()
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
class Restaurant():
"""餐馆类"""

def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.restaurant_type = cuisine_type
self.number_served = 0
# print(f"店铺名称:{self.restaurant_name},菜单:{self.restaurant_type},就餐人数:{self.number_served}")

def set_number_served(self, number_served):
self.number_served = number_served

def describe_restaurant(self):
print(f"餐馆名称:{self.restaurant_name},菜单:{self.restaurant_type}")

def open_restaurant(self):
print("正在营业")


class IceCreamStand(Restaurant):
def __init__(self, restaurant_name, cuisine_type):
super().__init__(restaurant_name, cuisine_type)
self.flavors = ['草莓', '巧克力', '芒果']

def describe_iceCream(self):
print(f"店铺名称:{self.restaurant_name},有三种口味冰激凌:{self.flavors}")


restaurant = Restaurant("一号店", "五星级酒店")
iceCream = IceCreamStand("冰激凌一号店", "菜单")
iceCream.describe_iceCream()
import time

start = time.time()
class User():
def __init__(self,first_name="姓",last_name="名"):
self.first_name = first_name
self.last_name = last_name
self.odometer_reading = 0
# self.describe_user()
# self.greet_user()

def describe_user(self):
print(f"名字:{self.first_name}{self.last_name}")

def greet_user(self):
print(f"Hello,{self.first_name}{self.last_name}")

def read_odometer(self):
print("里程数:",self.odometer_reading)

def update_odometer(self,mileage):
if mileage > self.odometer_reading:
self.odometer_reading = mileage
else:
print("不能回调里程数!")

user_1 = User("一叶","知秋")
print(user_1.read_odometer())
user_1.update_odometer(23)
print(user_1.read_odometer())
end = time.time()

print(end - start)

第十章 文件和异常

10.1 从文件中读取数据 .............................. 162

10.1.1 读取整个文件 ........................ 162

with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
使用文件步骤:
1、打开文件 open()
help(open)
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Open file and return a stream. Raise OSError upon failure.
小贴士:关键字 with 在不再需要访问文件后将其关闭,你只管打开文件,并在需要时使用它,Python自会在合适的时候自动将其关闭。
为什么不使用 open() and close() ? 因为如果程序存在bug,导致close()语句未执行,文件将不会关闭。未妥善地关闭文件可能会导致数据丢失或受损
2、读取文件 read(),返回一个长长的字符串存入contents中
小贴士:【但是我并未遇到!】相比于原始文件,该输出唯一不同的地方是末尾多了一个空行。为何会多出这个空行呢?因为read()到达文件末尾时返回一个空字符串,而将这个空字符串显示出来时就是一个空行。要删除多出来的空行,可在print语句中使用rstrip()

10.1.2 文件路径 ................................ 164

当前情况:
程序文件在:python_work 文件夹
要读取的文件在:python_work 下 text_files 文件夹
∵ 由于文件夹text_files位于文件夹 python_work 中,因此可使用相对文件路径来打开该文件夹中的文件

小贴士:

1、相对路径 vs 绝对路径,在使用绝对路径时候往往较长,存入变量后再进行传递给open()
2、在Windows系统中,在文件路径中使用反斜杠(\)而不是斜杠(/),但是在程序中需要使用 "/",如下:

10.1.2 文件路径

with open('text_files/pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())

10.1.3 逐行读取 ................................ 165

业务需求/应用场景:

1、你可能要遍历一个包含天气数据的文件,并使用天气描述中包含字样sunny的行。
2、在新闻报道中,你可能会查找包含标签的行,并按特定的格式设置它。

10.1.4 创建一个包含文件各行内容的列表.................................... 166

10.1.5 使用文件的内容 ..................... 166

10.1.6 包含一百万位的大型文件 ..... 168

10.1.7 圆周率值中包含你的生日吗 ........................................ 168

10.2 写入文件 .............................................. 169
10.2.1 写入空文件 ............................ 170
10.2.2 写入多行 ................................ 170
10.2.3 附加到文件 ............................ 171
10.3 异常 ..................................................... 172
10.3.1 处理 ZeroDivisionError异常 ........................................ 172
10.3.2 使用 try-except 代码块 ......... 173
10.3.3 使用异常避免崩溃 ................. 173
10.3.4 else 代码块 ............................ 174
10.3.5 处理 FileNotFoundError异常 ........................................ 175
10.3.6 分析文本 ................................ 176
10.3.7 使用多个文件 ........................ 177
10.3.8 失败时一声不吭 ..................... 178
10.3.9 决定报告哪些错误 ................. 179
10.4 存储数据 .............................................. 180
10.4.1 使用 json.dump()和 json.load() ..................................... 180
10.4.2 保存和读取用户生成的数据 ........................................ 181
10.4.3 重构 ........................................ 183
10.5 小结 ..................................................... 18

评论关闭