#.python学习笔记:在文本编辑器中新创建一个文件,写几句话老总结你至此学到的python知识
#其中‘In Python you can’ 打头。将这个文件命名为learning_python.txt.并将其存储到为本章学习目录下
#编写一个程序,它读取这个文件,并将你序偶写的内容打印三次:第一次打印时读取整个文件
#第二次打印时遍历文件对象,第三次打印时将各行存储在一个列表中,再在with代码块外打印它们
with open('learning_python.txt') as file_object:
contents = file_object.read()
print(contents)
filename = 'learning_python.txt'
with open(filename) as file_object1:
for line in file_object1:
print(line.rstrip())
print('\n')
with open(filename) as file_object2:
lines = file_object2.readlines()
for line in lines:
print(line.rstrip())
print('\n')
#.在1中完成的基础上,使用方法replace()将learning_python.txt中的Python替换成其它任意一门语言
filename = 'learning_python.txt'
with open(filename) as file_object1:
for line in file_object1:
line = line.replace('Python','Java')
print(line.rstrip())
#.访客:编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件guest.txt中
guest_names = input("Enter your name: ")
with open('guest.txt','a') as file_object:
file_object.write(guest_names + '\n')
#.访问名单:编写一个while循环,提示用户输入其名字。用户输入其名字后,在屏幕打印一句问候语
#并将一条访问记录添加到文件guest_book.txt中。确保这个文件中的每条记录都独占一行
while True:
print("Enter a to quit.")
names = input("Enter your name: ")
if names == 'q':
break
messages = "Hello! " + names
print(messages)
with open('guest_book.txt','a') as file_object:
file_object.write(messages + '\n')
#.关于编程的调查:编写一个while循环,询问用户为何喜欢编程。每当用户输入一个原因后,
#都将其添加到一个存储所有原因的文件中
while True:
print("Enter q to quit.")
reasons = input("Why do you like programming? ")
if reasons == 'q':
break
with open('reason_books.txt','a') as file_object:
file_object.write(reasons + '\n')
#.加法运算:提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字
#在这种情况下,当你尝试将输入转换为整数时,将引发TypeError异常。
#编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任一个值不是
#数字时都铺获TypeError异常,并打印一条友好的错误消息。
while True:
try:
first_number = int(input("Enter to the first number: "))
second_number = int(input("Enter to the second number: "))
sum = first_number + second_number
except ValueError:
print("Sorry,TypeError! please input again."
else:
print("The add result of two numbers:",sum)
#.猫和狗:创建两个文件cat.txt和dog.txt,在第一个文件中至少存储三只猫的名字
#在第二个文件中至少存储三条狗的名字。编写一个程序,尝试读取这些文件,
#并将其内容打印到屏幕上。将这些代码放在一个try-except代码块中,以便文件
#不存在是捕获FileNotFound错误,并打印一条友好的消息,将其中一个文件移到另一个
#地方,并确认except代码块中的代码将正确执行。
def Openfile(filename):
try:
with open(filename) as file_read:
contents = file_read.read()
print(contents.rstrip())
except FileNotFoundError:
print("Sorry,The file " + filename + " does not exit!")
filename = 'alice.txt'
Openfile(filename)
filename ='dog.txt'
Openfile(filename)
#.修改在2中所编写的except代码块,让程序不存在时一言不发
def Openfile(filename):
try:
with open(filename) as file_read:
contents = file_read.read()
print(contents.rstrip())
except FileNotFoundError:
pass
filename = 'alice.txt'
Openfile(filename)
filename ='dog.txt'
Openfile(filename)
#.常见单词:找一些你想分析的图书,使用方法count()来确定特定单词或短语在字符串中出现的次数
def Ludong(filename):
try:
with open(filename) as file_object:
contents = file_object.read()
print(contents.rstrip())
print("The word appears " + str(contents.lower().count('ludong')) + " times.")
except FileNotFoundError:
print("The file " + filename + " does not exit!")
filename = 'ludong.txt'
Ludong(filename)
#.喜欢的数字:编写一个程序,提示用户输入他喜欢的数字,并使用
#json.dump()将这个数字存储到文件中。再编写一个程序,从文件中读取这个值
#并打“I know your favorite number! It's 。。
import json
def StoreNumber():
#如果存储数字就获取它
filename = 'usernumber.json'
try:
with open(filename) as f_obj:
usernumber = json.load(f_obj)
except FileNotFoundError:
return None
else:
return usernumber
def get_new_number():
#提示用户输入数字
usernumber = input("Enter to your favorite number: ")
filename = 'usernumber.json'
with open(filename,'w') as f_obj:
json.dump(usernumber,f_obj)
return usernumber
def ReadNumber():
#读取数字
usernumber = StoreNumber()
if usernumber:
print("I Know your favorite number! It's " + str(usernumber))
else:
usernumber = get_new_number()
print("I'll remember the number: " + str(usernumber))
ReadNumber()
#.验证用户:最后一个remember_me.py版本假设用户要么已输入其用户名,要么是首次运行改程序。
#我们应修改这个程序,应对这样的情形:当前和最后一次运行该程序的用户并非同一个人
#因此,在greet_user()中打印欢迎用户回来的消息前,先询问用户名是否是对的
#如果不对,就调用get_new_username()让用户输入正确的用户名
import json
def get_stored_username():
#如果存储了用户名就获取它
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
def get_new_user():
#提示用户输入名字
username = input("What's your name? ")
filename = 'username.json'
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
return username
def greet_user():
#问候用户
username = get_stored_username()
if username:
ask = "Your username is " + username +"?"+ "if not,please input N, "
ask += "if yes,input Y: "
ask_msg = input(ask)
if ask_msg == 'Y':
print("Welcome back," + username + '!')
else:
username = get_new_user()
print("We'll remember you when you come back, " + username + '!')
else:
username = get_new_user()
print("We'll remember you when you come back, " + username + '!')
greet_user()