第十章介绍的是文件的读取和写入,以及异常的处理。总的来说,本章还是比较简单的,问题也不是很难。
打开文件用以下语句:
with open(file_name) as file_obj: 而关闭文件则用:file_obj.close()但是python会自动关闭文件的,人工关闭的话可能会出现错误,所以一般都不需要这条语句的。
读取文件有多种方法:
msg = file_obj.read() #read all
msg = file_obj.readline() #read a line
msg = file_obj.readlines() #read all lines对文件有写入操作的话,在打开文件的时候需要设置’w'或者‘a',‘a'参数使得写入问价时不会删除文件原来的内容,但是如果不需要的话可以不添加参数。 异常处理:
try:
pass
except:
pass#10-1
filename = 'learning_python.txt'
with open(filename) as file_object:
contents = file_object.read()
print(contents.rstrip())
print("\n")
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
print('\n')
#方法一
print_list = [] #先定义一个列表
with open(filename) as file_object:
for line in file_object:
print_list.append(line)
print(print_list)
#方法二
print('\n')
with open(filename) as file_object:
lines = file_object.readlines()
print(lines)
#10-2
with open(filename) as file_object:
for line in file_object:
print(line.replace('Python','C').rstrip())
#replace()函数为返回一个修改后的结果,但是并不修改字符串本身
#10-3
name = input("Please input your name:\n")
with open('guest.txt','w') as file_object:
file_object.write(name)
#10-4
with open('guest_book.txt','a') as file_obj:
name = "ds"
while name != "break":
name = input("Please input your name,and input break to end:\n")
file_obj.write(name)
#10-5
with open('reason.txt','a') as file_obj:
reason = 's'
while reason != 'a':
reason = input("Why do you like pyhton? press a to end:\n")
file_obj.write(reason)#10-6&7
try:
with open('number.txt') as file_obj:
while True:
try:
num1 = file_obj.readline()
num2 = file_obj.readline()
except:
print("There is no more digits.")
else:
if num1.rstrip().isdigit() and num2.rstrip().isdigit():
print(int(num1.rstrip())+int(num2.rstrip()))
# elif num1.rstrip().isdigit() or :
# print("The first input is not number")
#想判断怎么一个输入不是整数,但是不会0.0
elif num2.rstrip() == "":
break
else:
print("The input is not numbers!")
except:
print("There is no txt named number.txt")输入:
输出:
版权声明:本文为qq_37019740原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。