Python--文件和异常

Python–文件和异常

#从文件中读取数据
with open('digits.txt') as file_object:
   contents=file_object.read()
   print(contents)
#open()函数  饥饿收一个参数--文件名称,在执行文件所在的目录中寻找指定的文件,返回一个表示文件的对象
#关键字with再不需要访问文件后将其关闭;但是close()也可以关闭文件,可以如果过早调用close,会导致需要文件时(无法访问)
#使用方法read(),读取这个文件的全部内容,将其作为一个字符串存储在  变量中,打印变量,即可输出
#多出这个空行:因为read()到达文件末尾时返回一个空字符串,而这个空字符串显示出来就是一个空行;
print(contents.rstrip())   #删除字符串末尾的空白


#文件路径--打开不与运行的程序文件所在同一个目录的文件
#相对文件路径
with open('text_files\digits.txt') as file_object:
    contents=file_object.read()
    print(contents)
#绝对文字路径:--读取系统任何地方的文件   --反斜杠,转义标记,如果出现问题,那么就在开头单引号前加上r
file_path='D:\encourage\digits.txt'
with open(file_path) as file_object:
    contents=file_object.read()
    print(contents)

with open('digits.txt') as file_object:
    for line in file_object:
        print(line)
        print(line.rstrip())  #删除空行

#创建一个包含文件各行内容的列表--因为使用with时,open()返回的对象只能在with代码块中使用,如果想在with代码块之外访问文件内容,可以将文件各行存储在一个列表
with open('digits.txt') as file_object:
    lines=file_object.readlines()
for line in lines:
    print(line.rstrip())

#使用文件的内容
with open('digits.txt') as file_object:
    lines=file_object.readlines()
string=''
for line in lines:
    string+=line.rstrip()
print(string)
print(len(string))

#如果不想要原本在每行之前的空格
with open('digits.txt') as file_object:
    lines=file_object.readlines()
string=''
for line in lines:
    string+=line.strip()
print(string)
print(len(string))


#包含一百万位的大型文件--只要内存足够多
with open('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位中包含你的生日吗
with open('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'
with open(filename,'w') as file_object:  #w:写入模式,r读取模式,a附加模式     r+读取和写入;默认只读模式
    #w:如果你要写入的文件不存在,那么open()会自动创建;如果已经存在,那么会在返回对象前情况该文件
    file_object.write(str(520))
 #注意,只能将字符串写入文本,如果想写数值,那么先用str()转换

#写入多行
filename='digits.txt'
with open(filename,'w') as file_object:
    file_object.write(str(520)+'\n')   #注意换行符格式
    file_object.write('love you jenney\n')  #write()函数不会在写入的文本末尾添加换行符

#附加到文件--不会覆盖原来内容,而是添加到文件末尾;如果指定的文件不存在,会自动创建空文件
filename='digits.txt'
with open(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")
while True:
    first=input("First number :")
    if first=='q':
        break
    second=input("Second  number :")
    if second=='q':
        break
    try:
        answer=int(first)/int(second)
    except ZeroDivisionError:
        print("you can't divide by 0")  #除0失败,打印一条友好的消息
    else:
        print(answer)

#处理FileNoteNotFoundError异常
filename='digits.txt'
try:
    with open(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.")

#使用多个文本
def count_words(filename):
    """计算一个文件大致包含多少个单词"""
    try:
        with open(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)


def count_words(filename):
    """计算一个文件大致包含多少个单词"""
    try:
        with open(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)

#失败时一声不吭--找不到,但是不说话,但是可以运行其余的代码---pass
def count_words(filename):
    """计算一个文件大致包含多少个单词"""
    try:
        with open(filename) as file_object:
            contents=file_object.read()
    except FileNotFoundError:
        pass
 
    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)

#存储数据:--使用模块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'   #指定了将数字列表存储的文件名称
with open(filename,'w') as file_object:  #以写入模式打开,让json能够将数据写入
    json.dump(numbers,file_object)   #使用函数  将数字列表存储在文件 digits
    
import json
filename='digits.json'
with open(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'   #没有的话,自动创建
with open(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'
with open(filename) as file_object:
    username=json.load(file_object)
    print("welcome back !"+username+'!')

#将以上两个程序合并,当这个程序运行时,我们从username.json获取用户名
import json
#如果以前存储了用户名,就加载它
#否则,就提示用户输入用户名,并且存储他
filename='username.json'
try:
    with open(filename) as file_object:                   #打开文件username.json
        username=json.load(file_object)                  #如果文件存在,就将其用户名读取到内存中,然后执行else语句,打印欢迎
except FileNotFoundError:
    username=input("what is your name:")          #第一次运行,被提示输入用户名
    with open(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

def greet_user():
    """问候用户,指出名字"""
    filename='username.json'
    try:
        with open(filename) as file_object:
            username=json.load(file_object)
    except FileNotFoundError:
        username=input("what is your name?")
        with open(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()

#重构2
import json
def get_name():
    """如果已经存储了用户名,就获取它"""
    filename='username.json'
    try:
        with open(filename) as file_object:
            username=json.load(file_object)
    except FileNotFoundError:
        return None
    else:
        return username

def greet_user():
    """问候用户,指出名字"""
    username=get_name()
    if username:
        print("welcome back,"+username+'!')
    else:
        username=input("what is your name?")
        filename='username.json'
        with open(filename,'w') as file_object:
            json.dump(username,file_object)
            print("we'll remember you when you come back, "+username+'!')
greet_user()



发布了57 篇原创文章 · 获赞 54 · 访问量 2344

猜你喜欢

转载自blog.csdn.net/September_C/article/details/105187718