file_name ='..\\otherFiles\\YZU_english.txt'withopen(file_name)as file_object:for line in file_object:print(line.rstrip())#打印时,发现多出很多空白行。因为在这个文件中,每行的末尾都有一个看不见的换行符,调用print()时又会加上一个换行符#因此没放后面有两个换行符#要消除多余的换行符,用rstrip()
10.1.4 创建一个包含文件各行内容的列表
list=[]
file_path ='..\\otherFiles\\YZU_english.txt'withopen(file_path)as file_object:for line in file_object:list.append(line.rstrip())print(list)print(len(list))
正确方式!
readlines()从文件中读取每一行,并将其存储在一个列表中。
withopen(file_path)as file_object:
lines = file_object.readlines()for line in lines:print(line.rstrip())# print(type(lines)) #list类型
10.1.5 使用文件内容
file_path ='.\\pi_digits.txt'withopen(file_path)as file_object:
lines = file_object.readlines()
pi_string =''for line in lines:
pi_string += line.strip()print(pi_string)print(len(pi_string))
file_name3 ='..\\otherFiles\\chapter_10\\programming.txt'withopen(file_name2,'w')as file_object:
file_object.write("I love programming.2")
file_object.write("I love creating new games.2")
file_name3 ='..\\otherFiles\\chapter_10\\programming.txt'withopen(file_name2,'w')as file_object:
file_object.write("I love programming.3\n")
file_object.write("I love creating new games.3\n")
file_name3 ='..\\otherFiles\\chapter_10\\programming.txt'withopen(file_name2,'a')as file_object:
file_object.write("I love programming.4\n")
file_object.write("I love creating new games.4\n")
################################################practice################################################################### 2.1# 提示用户输入名字。用户做出响应后,将其名字写入文件guest.txt中
file_name4 ='..\\otherFiles\\chapter_10\\guest.txt'
flag =True
prompt ='Please, input your name.\n'
prompt +='otherwise, input q/Q to stop this program:'while flag:
message =input(prompt)if message.lower()!='q':print(f"Hello, {message}")withopen(file_name4,'a')as file_object:
file_object.write(message+'\n')else:
flag =False# 2.2# 编写一个while循环,询问用户为何喜欢编程
file_name5 ='..\\otherFiles\\chapter_10\\reasons.txt'
flag =True
prompt ='Why do you like programming?'
prompt +='\nOtherwise, enter q/Q to stop this program:'while flag:
message2 =input(prompt)if message2.lower()!='q':withopen(file_name5,'a')as file_object:
file_object.write(message2 +'\n')else:
flag =False
10.3 异常
10.3.1 处理ZeroDivisionError异常
print(5/0) #ZeroDivisionError: division by zero 不能用数除以0
try:#将导致错误的代码行放在一个try代码块中。若无错误,则跳过except代码块。若try中的语句出错,则运行except中的代码print(5/0)except ZeroDivisionError:print("You can't divide by zero!")
10.3.3 使用异常避免崩溃
print("Give me two numbers, and I'll divide them")print("Enter 'q' to quit")
flag3 =Truewhile flag3:
first_number =input('First number:')if first_number =='q':break
second_number =input('Second number')if second_number =='q':breaktry:#可能引发异常的代码放在try中print(float(first_number)/float((second_number)))except ZeroDivisionError:print("Errors occur,stop")
10.3.4 处理FileNotFoundError异常
找不到文件也可用try-except处理
file_name6 ='alict.txt'try:withopen(file_name6)as file_object:
content6 = file_object.read()except FileNotFoundError:print(f"{file_name6} not Found!")
10.3.5 分析文本
title ='Alice in wonderland'print(title.split())#split()方法以空格为分隔符将字符串拆成多个部分,并将这些部分都存储到一个列表中
file_name7 ='..\\otherFiles\\chapter_10\\alice.txt'try:withopen(file_name7, encoding='utf-8')as file_object:
content7 = file_object.read()except FileNotFoundError:print(f"Sorry file Not Found")else:#一些仅在try代码块成功执行时才需要运行的代码,这些代码放在else代码块中
lists = content7.split()
nums =len(lists)print(f"The file has about {nums} words.")
10.3.6 使用多个文件
defcount_words(filename):try:withopen(filename, encoding ='utf-8')as file_object:
content8 = file_object.read()except FileNotFoundError:print("Sorry file not Found")else:
lists = content8.split()
num =len(lists)print(f"{filename} has about {num} words.")# filename = '..\\otherFiles\\chapter_10\\alice.txt'# count_words(filename)
filelists =['..\\otherFiles\\chapter_10\\alice.txt','..\\otherFiles\\chapter_10\\moby_dick.txt','..\\otherFiles\\chapter_10\\little_women.txt','..\\otherFiles\\chapter_10\\abs.txt']for filelist in filelists:
count_words(filelist)
10.3.7 静默失败
并非每次捕捉到异常都需要告诉用户。有时你希望程序在发生异常时保持静默,就像没有发生一样继续运行
defcount2_words(filename):try:withopen(filename, encoding='utf-8')as file_object:
content8 = file_object.read()except FileNotFoundError:pass#错误发生时,不会有traceback,也不会有任何输出#pass语句还充当了占位符,提醒你这个地方什么都没做,并且以后也许要在这做些什么else:
lists = content8.split()
num =len(lists)print(f"{filename} has about {num} words.")for filelist in filelists:
count2_words(filelist)