知识归纳
- 读取整个文件
with open('pi_digits.txt')as file_object:
函数open()接受一个参数:要打开的文件的名称或文件路径;文件路径分为相对路径和绝对路径,切记在文件路径中使用反斜杠(\)而不是斜杠;关键字with在不再需要访问文件后将其关闭,open返回的文件对象只在with代码块内可用
2. 逐行读取 for循环
3. 创建包含文件各行内容的列表:在with代码块外使用文件内容,可将文件各行存储在一个列表中
4. 使用文件的内容:注意若读取文件内容是数字且作为数值用的时候必须使用函数int()来将其转换为整数或float()转换成浮点数
5. 写入文件:
with open(filename,'w')as file_object:
file_object.write('neirong')
‘w’:以写入模式打开文件
‘r’: 以读取模式打开文件
‘a’:以附加模式打开文件
‘r+’:以读取和写入模式打开文件
注意:若open打开的文件不在会创建新的文件,但以‘w’模式打开已存在的文件,则该文件会首先提前清空;若将数值数据存储到文本文件中,必须先使用函数str()将其转换为字符串格式
动手试一试
- python学习笔记:在文本编辑器中新创建一个文件,写几句话来总结你至此学到的python知识,其中‘In Python you can’ 打头。将这个文件命名为test1.txt.并将其存储到为本章学习目录下,编写一个程序,它读取这个文件,并将你所写的内容打印三次:第一次打印时读取整个文件,第二次打印时遍历文件对象,第三次打印时将各行存储在一个列表中,再在with代码块外打印它们
with open('test1.txt')as file:
content = file.read()
print(content) #读取整个文件
with open('test1.txt')as file:
for line in file:
print(line.rstrip()) #遍历整个文件
with open('test1.txt')as file:#打印时将各行存储在一个列表中
lines = file.readlines()
for line in lines:
print(line.rstrip())
- 在1中完成的基础上,使用方法replace()将test1.txt中的Python替换成其它任意一门语言
with open('test1.txt')as file:
for line in file:
line = line.replace('Python','Java')
print(line.strip())
- 访客:编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件guest.txt中
with open('test2.txt','w')as file:
print('Please input a number: ')
file.write(input())
4. 访问名单:编写一个while循环,提示用户输入其名字。用户输入其名字后,在屏幕打印一句问候语并将一条访问记录添加到文件guest_book.txt中。确保这个文件中的每条记录都独占一行
with open('guest_book.txt','w')as file:
while True :
print("You can input a q to end at any time.")
name = input('Please input your name: ')
if name == 'q':
break
else:
print('Welcome!'+name)
file.write(name+'\n')
5. 关于编程的调查:编写一个while循环,询问用户为何喜欢编程。每当用户输入一个原因后,都将其添加到一个存储所有原因的文件中
with open('test3.txt','w')as file:
while True :
print("You can input a q to end at any time.")
name = input('Please input your reason for loving coding: ')
if name == 'q':
break
file.write(name+'\n')
- 1.加法运算:提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字在这种情况下,当你尝试将输入转换为整数时,将引发TypeError异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任一个值不是数字时都铺获TypeError异常,并打印一条友好的错误消息。
while True:
try:
first_number = int(input('first number: '))
second_number = int(input('second number: '))
result = first_number + second_number
except ValueError:
print('Please enter number again.')
else:
print('The result is: ',result)
结果:
注意:出现过以下错误,原因是在代码中的数字输入没有用int进行转换导致相加就是简单的字符相加而不是数字相加得到的结果
7. 猫和狗:创建两个文件cat.txt和dog.txt,在第一个文件中至少存储三只猫的名字在第二个文件中至少存储三条狗的名字。编写一个程序,尝试读取这些文件,并将其内容打印到屏幕上。将这些代码放在一个try-except代码块中,以便文件不存在时捕获FileNotFound错误,并打印一条友好的消息,将其中一个文件移到另一个地方,并确认except代码块中的代码将正确执行。
#创建文件
with open('cat.txt','w')as cat:
cat.write('coco ')
cat.write('lala ')
cat.write('mimi ')
with open('dog.txt','w')as dog:
dog.write('aa ')
dog.write('bb ')
dog.write('cc ')
#定义读取文件函数
def file(filename):
try:
with open(filename) as f:
content = f.read()
print(content)
except FileNotFoundError:
print('No found file.Please check it.')
filename1 = 'cat.txt'
filename2 = 'dog.txt'
filename3 = 'pig.txt'
file(filename1)
file(filename2)
file(filename3)
结果:
coco lala mimi
aa bb cc
No found file.Please check it.
- 修改在7中所编写的except代码块,让程序不存在时一言不发
- 常见单词:找一些你想分析的图书,使用方法count()来确定特定单词或短语在字符串中出现的次数
filename = 'beiying.txt'
try:
with open(filename) as f:
content = f.read()
print(content)
except FileNotFoundError:
print('The file no exit.')
else:
words = content.split()
num = content.count('x')
print(num)
10. 喜欢的数字:编写一个程序,提示用户输入他喜欢的数字,并使用json.dump()将这个数字存储到文件中。再编写一个程序,从文件中读取这个值并打“I know your favorite number! It’s …
import json
number = input('Please enter numbers you like: ')
with open('num','w')as f:
json.dump(number,f)
with open('num') as f1:
numbers = json.load(f1)
print("I know your favorite number! It's' "+numbers)
- 验证用户:最后一个remember_me.py版本假设用户要么已输入其用户名,要么是首次运行改程序。我们应修改这个程序,应对这样的情形:当前和最后一次运行该程序的用户并非同一个人,因此,在greet_user()中打印欢迎用户回来的消息前,先询问用户名是否是对的,如果不对,就调用get_new_username()让用户输入正确的用户名
import json
def get_stored_username():#已存储用户
filename = 'username.json'
try:
with open(filename) as f:
username = json.load(f)
except FileNotFoundError:
return None
def get_new_user():#新用户
username = input('What`s your name? ')
filename = 'username.json'
with open(filename,'w')as f:
json.dump(username,f)
return username
def greet_user():#问候用户
username = get_stored_username()
if username:
info = 'Your username is '+ username + 'If not,Please enter an N,If yes,enter a Y.'
infomation = input(info)
if infomation == 'Y':
print('Welcome! '+username)
else:
username = get_new_user()
print('Nice to meet you '+username)
else:
username = get_new_user()
print('Nice to meet you '+username)
greet_user()
小结:
在本章学习了如何使用文件,如何一次性读取整个文件;如何每次一行的方式读取文件内容;如何写入文件以及将文本附加到文件末尾;什么是异常以及如何处理程序有可能发生的异常;如何存储python数据结构,保存用户提供的信息避免每次运行程序都要重新提供。