第十章 文件和异常

10.1从文件中读取数据

读取整个文件

with open('pi_digits.txt') as file_object:
    contents=file_object.read()#read读取后,会返回一个空行
    print(contents)

with可以自动关闭文件,比colse()好用,建议使用with

print(contents.rstrip())

文件路径

windows系统在相对路径打开文件:with open(‘text_files\filename.txt’) as file_object:


相对路径指的是程序和文件在同一文件夹中

file_path = ‘C:\Users\ehmatthes\other_files\text_files\filename.txt’


with open(file_path) as file_object:


绝对路径指的是程序和文件不在同一文件夹中

逐行读取
filename='pi_digits.txt'

with open(filename) as file_object:
    for line in file_object:
        print(line)

为什么会有两行?1.在文件,每行末尾有一个换行符2.print语句后会加上换行符

filename='pi_digits.txt'

with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())
创建一个包含文件夹各行内容的列表
#将with代码块中将文件各行储存在一个列表中,再在with代码块打印它们
filename='pi_digits.txt'

with open(filename) as file_object:
    lines=file_object.readlines()#读取每一行,并将其储存在列表中
    
for line in lines:
    print(line.rstrip())
        
使用文件中的内容
filename='pi_digits.txt'

with open(filename) as file_object:
    lines=file_object.readlines()#读取每一行,并将其储存在列表中
    
pi_string=' '
for line in lines:
    pi_string+=line.rstrip()
    
print(pi_string)
filename='pi_digits.txt'

with open(filename) as file_object:
    lines=file_object.readlines()#读取每一行,并将其储存在列表中
    
pi_string=' '
for line in lines:
    pi_string+=line.strip()
    
print(pi_string)
包含一百万的大型文件
filename='chapter_10/pi_million_digits.txt'

with open(filename) as file_object:
    lines=file_object.readlines()
    
pi_string=' '
for line in lines:
    pi_string += line.strip()
    
print(pi_string[:52]+ "...")     
圆周率包含你的生日么
#确定某个人的生日是否包含在圆周率值的前1 000 000位中
filename='chapter_10/pi_million_digits.txt'

with open(filename) as file_object:
    lines=file_object.readlines()
    
pi_string=' '
for line in lines:
    pi_string += line.strip()
    
birthday=input('Enter your birthday:')

if birthday in pi_string:
    print('your birthday appears in the first million digits of pi!')
else:
    print('your birth day does not in the first million digits of pi')
#10-1
filename='chapter_10/python_learning.txt'

with open(filename) as file:
    lines=file.read()
    print(lines)
    

filename='chapter_10/python_learning.txt'

with open(filename) as file:
    for line in file:
        print(line)
filename='chapter_10/python_learning.txt'

with open(filename) as file:
    lines=file.readlines()
    
print(lines)
#10-2
filename='chapter_10/python_learning.txt'

with open(filename) as file:
    lines=file.read()
    a=lines.replace('python','c')#替换之后原来是返回一个新的copy,因此如果不赋值,还是原来结果
    print(a)


10.2写入文件

写入空文件
filename='programming.txt'

with open(filename,'w') as file_object:#w告诉python你要使用写入模式,默认是以只读模式
    file_object.write('I love programming')
写入多行
filename='programming.txt'

with open(filename,'w') as file_object:
    file_object.write('I love programming')
    file_object.write('I love creating games')

如果打开文件,发现两行内容连在一起,因为你没有指定换行符

#不会连在一起
filename='programming.txt'

with open(filename,'w') as file_object:
    file_object.write('I love programming\n')
    file_object.write('I love creating games\n')
附加到文件
filename='programming.txt'

with open(filename,'a') as file_object:#'a'为附加模式:不会覆盖,而是将写入内容加到文件末尾
    file_object.write('I aslo love finding meaning in large datasets\n')
    file_object.write('I love apps that can run in a browser\n')
with open(filename) as f:
    lines=f.readlines()
    
lines
#10-3

input_name=input('Please input your name:')

filename='guest.txt'

with open(filename,'w') as file:
    file.write(input_name)
with open(filename) as file:
    name=file.readlines()
    
name
#10-4
filename='guest_book.txt'

with open(filename,'w') as file:
    while name != 'quit':
        name=input('Please input your name:')
        print('Hello,'+name)
        file.write(name+' access \n')
with open(filename) as file:
    name=file.read()
    
name

10.3异常

try-except常常用来处理异常

处理zerodivisionerror异常
#这种错误是出现了5/0这种情况
使用try-exept代码块
try:
   如果成功执行此行代码,不成功执行except
 except 错误类型:
    try失败,运行此代码
try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero")
使用异常避免崩溃
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")

while True:
    first_number=input('\nFirst number:')
    if first_number =='q':
        break
    
    second_number=input('Second number:')
    if second_number == 'q':
        break
        
    answer=float(first_number)/float(second_number)
    print(answer)
#如果执行除数为0的运算,程序会崩溃
else代码块
try:
    code
except;
    try失败,至此此code
else:
    try成功,执行此code
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")

while True:
    first_number=input('\nFirst number:')
    if first_number =='q':
        break
    
    second_number=input('Second number:')
    if second_number == 'q':
        break
    try:   
        answer=float(first_number)/float(second_number)#可能引发异常的代码放在try语句中
    except ZeroDivisionError:
        print("You can't divide by zero")
    else:
        print(answer)
处理FileNotFoundError
filename='alice.txt'

with open(filename) as f_obj:
    contents=f_obj.read()

这是找不到文件所引起的错误,可使用try-except,其中open是引发异常的代码

filename='alice.txt'

try:
    with open(filename) as f_obj:
        contents=f_obj.read()
except FileNotFoundError:
    msg="Sorry, the file " + filename + " does not exist."
    print(msg)
分析文本
title = "Alice in Wonderland"
title.split()#split函数将字符串拆成多个部分,空格为分隔符
filename='chapter_10/alice.txt'

try:
    with open(filename,encoding='utf-8') as f_obj:
        contents=f_obj.read()
except FileNotFoundError:
    msg="Sorry, the file " + filename + " does not exist."
    print(msg)
else:
    
    words=contents.split()
    num_words=len(words)
    print('The file '+filename+' has about '+str(num_words)+" words.")
使用多个文件
def count_words(filename):
    #此函数用来计算一个文件中大约包含多少单词
    
    try:
        with open(filename,encoding='utf-8') as f_obj:
            contents=f_obj.read()
    except FileNotFoundError:
        msg="Sorry, the file " + filename + " does not exist."
        print(msg)
    else:
        #计算文件大致包含多少单词
        words=contents.split()
        num_words=len(words)
        print('The file '+filename+' has about '+str(num_words)+" words.")
    
filename='chapter_10/alice.txt'
count_words(filename)
#使用不再目录内的文件
filenames = ['alice.txt', 'siddhartha.txt', 
             'moby_dick.txt', 'little_women.txt']
for filename in filenames:
    count_words(filename)
#找到文件
filenames = ['chapter_10/alice.txt', 'chapter_10/siddhartha.txt', 
             'chapter_10/moby_dick.txt', 'chapter_10/little_women.txt']
for filename in filenames:
    count_words(filename)
失败时一声不吭
def count_words(filename):
    #此函数用来计算一个文件中大约包含多少单词
    
    try:
        with open(filename,encoding='utf-8') as f_obj:
            contents=f_obj.read()
    except FileNotFoundError:
            pass#告诉python什么都不做
    else:
        #计算文件大致包含多少单词
        words=contents.split()
        num_words=len(words)
        print('The file '+filename+' has about '+str(num_words)+" words.")
    
#不会告诉你关于siddhartha的信息
filenames = ['chapter_10/alice.txt', 'siddhartha.txt', 
             'chapter_10/moby_dick.txt', 'chapter_10/little_women.txt']
for filename in filenames:
    count_words(filename)
#10-6加法运算

number1=input('Please input number1:')
number2=input('Please input number2:')

try:
    sum_number=float(number1)+float(number2)
except ValueError:
    print('The type is rerror')
else:
    print(sum_number)
number1=input('Please input number1:')
number2=input('Please input number2:')
    
while number1 !='q' and number2 !='q':

    try:
        sum_number=float(number1)+float(number2)
    except ValueError:
        print('The type is rerror')
    else:
        print(sum_number)
#10-8
filenames=['cats.txt','dogs.txt']

for filename in filenames:
    try:
        with open(filename) as file:
            name=file.read()

    except FileNotFoundError:
        print(filename+'不在此目录')

    else: 
        print(name)
#10-9
filenames=['cats.txt','dogs.txt']

for filename in filenames:
    try:
        with open(filename) as file:
            name=file.read()

    except FileNotFoundError:
        pass

    else: 
        print(name)
#10-10
filename='chapter_10/alice.txt'

with open(filename,encoding='utf-8') as file:
    lines=file.read()
    
lines.lower().count('the')

10.4储存数据

使用json模块

使用json.dump()和json.load()

json.dump():接受存储的数据以及文件对象两个参数

import json

numbers = [2, 3, 5, 7, 11, 13]

filename='number.json'
with open(filename,'w') as f_obj:
    json.dump(numbers,f_obj)
#json.load()用于加载数据
filename='number.json'
with open(filename) as f_obj:
    numbers=json.load(f_obj)
    
print(numbers)
10.4.2保存和读取用户生成的数据
username=input('What is your name?')

filename='user.json'
with open(filename,'w') as f_obj:
    json.dump(username,f_obj)
    print("We'll remember you when you come back, " + username + "!")
#向用户问候

filename='user.json'

with open(filename) as f_obj:
    username=json.load(f_obj)
    print('Welcome back,'+username+"!")
filename='user.json'
#如果能加载json,则打印
#如果不能打印,新建一个,并打印信息

try:
    with open(filename) as f_obj:
        username=json.load(f_obj)
except FileNotFoundError:
    username=input("What is your name?")
    with open(filename,'w') as f_obj:
        json.dump(username,f_obj)
        print("We'll remember you when you come back, " + username + "!")
else:
    print('Welcome back,'+username+"!")
10.4.3重构

重构:将代码划分为一系列完成具体工作的函数

def greet_user():
    """问候用户,并指出用户的名字"""
    filename='user.json'
    #如果能加载json,则打印
    #如果不能打印,新建一个,并打印信息

    try:
        with open(filename) as f_obj:
            username=json.load(f_obj)
    except FileNotFoundError:
        username=input("What is your name?")
        with open(filename,'w') as f_obj:
            json.dump(username,f_obj)
            print("We'll remember you when you come back, " + username + "!")
    else:
        print('Welcome back,'+username+"!")
def get_stored_username():
    """如果储存文件,就获取用户名"""
    filename='user.json'
    
    try:
        with open(filename) as f_obj:
            username=json.load(f_obj)
    except FileNotFoundError:
        return none
    else:
        return username
def greet_user():
    """成功获取用户名,打印消息。如果没有,就提示用户输入用户名"""
    username=get_stored_username()
    
    if username:
        print('Welcome back, '+username+"!")
    else:
        username=input('What is your name?')

        filename='user.json'
        with open(filename,'w') as f_obj:
            json.dump(username,f_obj)
            print("We'll remember you when you come back, " + username + "!")
greet_user()
def get_new_username():
    """提示用户输入用户名"""
    username=input('What is your name?')
    filename='user.json'
    with open(filename,'w') as f_obj:
        json.dump(username,f_obj)
        print("We'll remember you when you come back, " + username + "!")
    return username
#10-11
input_info=input("The favorite number:")

filename='number_fav.json'

with open(filename,'w') as f:
    json.dump(input_info,f)
The favorite number:7
with open(filename) as f:
    fav_num=json.load(f)
fav_num
'7'
#10-12
filename='number_fav.json'

try:
    with open(filename) as f:
        fav_num=json.load(f)
    
except :
    number=input('please input your favorite number:')
    filename='number_fav.json'

    with open(filename,'w') as f:
        json.dump(number,f)

else:
    print(fav_num)
7

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值