#从文件中读取数据withopen('digits.txt')as file_object:
contents=file_object.read()print(contents)#open()函数 饥饿收一个参数--文件名称,在执行文件所在的目录中寻找指定的文件,返回一个表示文件的对象#关键字with再不需要访问文件后将其关闭;但是close()也可以关闭文件,可以如果过早调用close,会导致需要文件时(无法访问)#使用方法read(),读取这个文件的全部内容,将其作为一个字符串存储在 变量中,打印变量,即可输出#多出这个空行:因为read()到达文件末尾时返回一个空字符串,而这个空字符串显示出来就是一个空行;print(contents.rstrip())#删除字符串末尾的空白#文件路径--打开不与运行的程序文件所在同一个目录的文件#相对文件路径withopen('text_files\digits.txt')as file_object:
contents=file_object.read()print(contents)#绝对文字路径:--读取系统任何地方的文件 --反斜杠,转义标记,如果出现问题,那么就在开头单引号前加上r
file_path='D:\encourage\digits.txt'withopen(file_path)as file_object:
contents=file_object.read()print(contents)withopen('digits.txt')as file_object:for line in file_object:print(line)print(line.rstrip())#删除空行#创建一个包含文件各行内容的列表--因为使用with时,open()返回的对象只能在with代码块中使用,如果想在with代码块之外访问文件内容,可以将文件各行存储在一个列表withopen('digits.txt')as file_object:
lines=file_object.readlines()for line in lines:print(line.rstrip())#使用文件的内容withopen('digits.txt')as file_object:
lines=file_object.readlines()
string=''for line in lines:
string+=line.rstrip()print(string)print(len(string))#如果不想要原本在每行之前的空格withopen('digits.txt')as file_object:
lines=file_object.readlines()
string=''for line in lines:
string+=line.strip()print(string)print(len(string))#包含一百万位的大型文件--只要内存足够多withopen('digits.txt')as file_object:
lines=file_object.readlines()
string=''for line in lines:
string+=line.strip()#删除空格print(string[:52]+'...')#只输出前52位(因为整数和小数点也分别占一位print(len(string))#圆周率的前1000位中包含你的生日吗withopen('digits.txt')as file_object:
lines=file_object.readlines()
string=''for line in lines:
string+=line.strip()#删除空格
birth=input("enter your birthday,in the form mmddyy: ")if birth in string:print("your birth is in the first thousand digits of pi")else:print("your birth is not in the first thousand digits of pi")#保存数据的最简单方式就是写到文件中#写入空文件
filename='digits.txt'withopen(filename,'w')as file_object:#w:写入模式,r读取模式,a附加模式 r+读取和写入;默认只读模式#w:如果你要写入的文件不存在,那么open()会自动创建;如果已经存在,那么会在返回对象前情况该文件
file_object.write(str(520))#注意,只能将字符串写入文本,如果想写数值,那么先用str()转换#写入多行
filename='digits.txt'withopen(filename,'w')as file_object:
file_object.write(str(520)+'\n')#注意换行符格式
file_object.write('love you jenney\n')#write()函数不会在写入的文本末尾添加换行符#附加到文件--不会覆盖原来内容,而是添加到文件末尾;如果指定的文件不存在,会自动创建空文件
filename='digits.txt'withopen(filename,'a')as file_object:
file_object.write('I also love to sursive.\n')
file_object.write('i also love you ,not him\n')
#异常#python 使用被称为异常的特殊对象来管理 程序执行期间发生的错误,每当发生让pyhton不知所措的错误时,他都会创建一个异常对象#如果编写了处理异常的代码,程序将继续运行,否则,程序停止,显示trackback,其中包含有关异常的报告#异常是用try-expect代码块写的,使用try-expect时,即便出现异常,程序也会运行:显示错误信息,#处理ZeroDivisionError异常try:print(5/0)except ZeroDivisionError:print("you can't divide by zero!")#ZeroDivisionError是一个异常对象,此时,python停止运行,并且指出错误 ,此时,写入try-expect代码块,可以处理好,而且不影响之后的代码#使用异常避免崩溃print("give me two number,i'll divide them")print("enter 'q' to quit at any time")whileTrue:
first=input("First number :")if first=='q':break
second=input("Second number :")if second=='q':breaktry:
answer=int(first)/int(second)except ZeroDivisionError:print("you can't divide by 0")#除0失败,打印一条友好的消息else:print(answer)#处理FileNoteNotFoundError异常
filename='digits.txt'try:withopen(filename)as file_object:#python无法读取不存在的文件,会引发异常
contents=file_object.read()except FileNotFoundError:
message="sorry,the file"+filename+"does not exist"print(message)#分析文本:else:#计算文件大约多少个单词
words=contents.split()#方法split(),根据一个字符串创建一个列表,以空格为分隔符拆分字符串
num_words=len(words)print("the file "+filename+"has about "+str(num_words)+" words.")#使用多个文本defcount_words(filename):"""计算一个文件大致包含多少个单词"""try:withopen(filename)as file_object:
contents=file_object.read()except FileNotFoundError:
message="sorry,the file "+filename+" does not exist"print(message)else:#计算文件大致包含多少个单词"""
words=contents.split()
num_words=len(words)print("the file "+filename+" has about "+str(num_words)+" words")
filename="digits.txt"
count_words(filename)defcount_words(filename):"""计算一个文件大致包含多少个单词"""try:withopen(filename)as file_object:
contents=file_object.read()except FileNotFoundError:
message="sorry,the file "+filename+" does not exist"print(message)else:#计算文件大致包含多少个单词"""
words=contents.split()
num_words=len(words)print("the file "+filename+" has about "+str(num_words)+" words")
filenames=['alice.txt','digits.txt','text_files\commom errors.txt']#第一个文件并不存在,但丝毫不影响程序进行for filename in filenames:
count_words(filename)#失败时一声不吭--找不到,但是不说话,但是可以运行其余的代码---passdefcount_words(filename):"""计算一个文件大致包含多少个单词"""try:withopen(filename)as file_object:
contents=file_object.read()except FileNotFoundError:passelse:#计算文件大致包含多少个单词"""
words=contents.split()
num_words=len(words)print("the file "+filename+" has about "+str(num_words)+" words")
filenames=['alice.txt','digits.txt','text_files\commom errors.txt']#第一个文件并不存在,但丝毫不影响程序进行for filename in filenames:
count_words(filename)#存储数据:--使用模块json来存储数据---将简单的python数据结构转储到文件中,在程序再次运行时加在该文件中的数据#使用json在python程序之间分项数据,JSON数据格式并非pyhton专用,可以与使用其他编程语言的人互享#全名:JavaScript Object Notation,最初为JavaScript开发,但最后形成了一种格式#使用json.dump()和json.load()import json
numbers=[2,3,5,7,11]
filename='digits.json'#指定了将数字列表存储的文件名称withopen(filename,'w')as file_object:#以写入模式打开,让json能够将数据写入
json.dump(numbers,file_object)#使用函数 将数字列表存储在文件 digitsimport json
filename='digits.json'withopen(filename)as file_object:
numbers=json.load(file_object)#加载存储在digits.json中的信息,储存在变量number中,最后打印print(numbers)#保存和读取用户生成的数据--如果不以某种方式进行存储 ,等程序停止运行时,用户的信息将会丢失import json
username=input("what is your name :")
filename='username.json'#没有的话,自动创建withopen(filename,'w')as file_object:
json.dump(username,file_object)print("we'll remember you when you come back, "+username+'!')#编写一个程序,向其名字被存储的用户发出问候import json
filename='username.json'withopen(filename)as file_object:
username=json.load(file_object)print("welcome back !"+username+'!')#将以上两个程序合并,当这个程序运行时,我们从username.json获取用户名import json
#如果以前存储了用户名,就加载它#否则,就提示用户输入用户名,并且存储他
filename='username.json'try:withopen(filename)as file_object:#打开文件username.json
username=json.load(file_object)#如果文件存在,就将其用户名读取到内存中,然后执行else语句,打印欢迎except FileNotFoundError:
username=input("what is your name:")#第一次运行,被提示输入用户名withopen(filename,'w')as file_object:
json.dump(username,file_object)#存储用户名print("we'll remember you when you come back, "+usrname+'!')#打印欢迎else:print("welcome back "+username+'!')#重构--将代码划分为一系列完成具体工作的函数import json
defgreet_user():"""问候用户,指出名字"""
filename='username.json'try:withopen(filename)as file_object:
username=json.load(file_object)except FileNotFoundError:
username=input("what is your name?")withopen(filename,'w')as file_object:
json.dump(username,file_object)print("we'll remember you when you come back,"+username+'!')else:print("welcome back,"+username+'!')
greet_user()#重构2import json
defget_name():"""如果已经存储了用户名,就获取它"""
filename='username.json'try:withopen(filename)as file_object:
username=json.load(file_object)except FileNotFoundError:returnNoneelse:return username
defgreet_user():"""问候用户,指出名字"""
username=get_name()if username:print("welcome back,"+username+'!')else:
username=input("what is your name?")
filename='username.json'withopen(filename,'w')as file_object:
json.dump(username,file_object)print("we'll remember you when you come back, "+username+'!')
greet_user()