Python学习笔记——十、文件和异常

学习书籍:《Python编程:从入门到实践》 Eric Matths著

一、   读取文件

1.   读取操作

# 从文件中读取数据  
# with语句,让open函数不需要显性得调用close函数进行关闭
with open('pi_digits.txt') as file_object:  
    contents = file_object.read()  
    print(contents.rstrip())  

  • l  with语句,让open函数不需要显性得调用close函数进行关闭

    l  open函数,打开当前目录下的文件,返回一个文件对象

    l  as语句,指定假名

    l  文件对象read方法,返回一个包含所有文件内容的字符串

    l  rstrip方法,去除字符串右端空字符(包括空格、制表符、换行符等)。

2.   文件路径

l  相对路径:相对当前工作目录的路径

注:linux/unix衍生的操作系统中文件夹分隔符为”斜杠,/“,而windows操作系统中文件夹分隔符为“反斜杠\”

l  绝对路径:系统中的路径的表示。由于跨平台性较差,一般不使用。

3.   逐行读取

# 逐行读取  
# 使用相对路径  
file_name = 'text_files/pi_digits.txt'  
with open(file_name) as file_object:  
    """使用for循环对文件对象进行遍历,能够提取每一行""" 
    for line in file_object:  
        print(line.rstrip())  

l  使用文件名变量file_name,便于修改。

l  对文件对象使用使用for循环遍历,可以提取每一行,包括行尾的换行符等空白符。

4.   创建包含文件各行内容的列表

# 使用文件对象的readlines方法创建包含文件各行的列表
file_name = 'text_files/pi_digits.txt'  
with open(file_name) as file_object:  
    lines = file_object.readlines()  
  
for line in lines:  
    print(line.rstrip())  

l  readlines方法返回一个包括文件各行内容的列表,各行内容包括换行符。

5.   使用文件内容

1)   创建包含文件内容的pi字符串

# 使用文件内容  
file_name = 'text_files/pi_digits.txt'  
with open(file_name) as file_object:  
    lines = file_object.readlines()  
  
# 创建表示π的字符串  
str_pi = ''  
for line in lines:  
    str_pi += line.strip()  
print(str_pi)  

str_pi变量必须先存在再作”+=”操作。

2)   处理包含小数点后100万位的小数

# 使用文件内容,包含一百万位的大文件  
file_name = 'text_files/pi_million_digits.txt'  
with open(file_name) as file_object:  
    lines = file_object.readlines()  
  
# 创建表示π的字符串  
str_pi = ''  
for line in lines:  
    str_pi += line.strip()  
# 提取小数点后50位  
print(str_pi[:52] + "...")  
print(len(str_pi))  

l  使用切片,表示0~51个元素,也就是前52个元素,str_pi[:52]

二、   写入文件

1.   写入操作

# 写入一个空文件  
file_name = 'programming.txt'  
# open打开一个文件,使用'w'参数,表示清除内容并写入。如果不存在这个文件,则默认新建一个。  
with open(file_name, 'w') as file_object:  
    file_object.write('I love programming.')    # write方法,写入  

l  open函数打开一个待写入的文件,使用’w’参数

l  文件对象的wirte方法将字符串写入文本文件

2.   写入多行文本

# 写入一个空文件  
file_name = 'programming.txt'  
# open打开一个文件,使用'w'参数,表示清除内容并写入。如果不存在这个文件,则默认新建一个。  
with open(file_name, 'w') as file_object:  
    file_object.write('I love programming.\n')  # write方法,写入  
    file_object.write('I love morning.\n')  
    file_object.write('I hate rain.\n')  

l  文件对象的write方法把字符串写入,并不会自动加入换行符,因此需要手动添加。

3.   追加内容

with open(file_name, 'a') as file_object:  
    file_object.write('I alse like finding infomation from large datasets.\n') 

l  追加内容,open函数使用’a’,append

三、   异常

1.   处理ZeroDivisionError异常

try:  
    print(5/0)  
except ZeroDivisionError:  
    print("You can't divide by zero.")  

l  try语句,尝试执行某语句;except语句,尝试捕捉某异常,如果捕捉到,则执行下面语句。

2.   使用try语句提升程序健壮性,避免崩溃

Demo,一个除法程序

print("Give me two numbers, I'll divide them.")  
print("Enter 'q' to quit anytime.")  
while True:  
    first_num = input("First_num: ")  
    if first_num == 'q':  
        break  
    second_num = input("Second_num: ")  
    if second_num == 'q':  
        break  
    try:  
        answer = int(first_num)/int(second_num)  
    except ZeroDivisionError:  
        print("You can not divide a num by zero!")  
    else:  
        print(answer)  

l  在需要用户输入之前,要有提示。要说明怎样结束程序

l  else代码块,依赖于try代码成功执行,则执行。

3.   处理FileNotFoundError异常

# 找不到文件的错误,FileNotFoundError  
file_name = 'alice.txt'  
try:  
    with open(file_name) as file_object:  
        contents = file_object.read()  
except FileNotFoundError:  
    msg = "Sorry, the file " + file_name + " doesn't exit."  
    print(msg)  

l  即使在文件不存在的情况下,程序不崩溃。

4.   分析文本

# 找不到文件的错误,FileNotFoundError  
file_name = 'text_files/alice.txt'  
try:  
    with open(file_name) as file_object:  
        contents = file_object.read()  
except FileNotFoundError:  
    msg = "Sorry, the file " + file_name + " doesn't exit."  
    print(msg)  
else:  
    # 处理文本  
    words = contents.split()  
    msg = "The file " + file_name + " has about " + str(len(words)) + " words." 
    print(msg)  

l  split方法,将字符串以空白符分隔

5.   处理多个文件

def count_words(file_name):  
    """数文本文件单词数"""  
    try:  
        with open(file_name) as file_object:  
            contents = file_object.read()  
    except FileNotFoundError:  
        msg = "Sorry, the file " + file_name + " doesn't exit."  
        print(msg)  
    else:  
        # 处理文本  
        words = contents.split()  
        msg = "The file " + file_name + " has about " + str(len(words)) + " words."  
        print(msg)  
  
file_names = ['alice.txt', 'little_women.txt', 'moby_dick.txt']  
for file_name in file_names:  
    count_words(file_name)  

l  变成函数后,相应得需要更新注释

l  对于列表,使用for循环遍历的方法

l  处理异常,可以使用pass语句,将跳过异常

四、   存储数据

使用JSON(JavaScript Object Notation)格式。

json.dump(), json.load()两个方法分别进行存储和调用。

# number_writer.py  
# 通过json.dump()方法输出一组数  
import json  
  
file_name = 'numbers.json'  
numbers = [1, 3, 7, 9]  
with open(file_name, 'w') as file_object:  
    json.dump(numbers, file_object)  

l  导入json包

l  json.dump()指定源和要被导入数据的文件对象

2.   调用json数据

# number_reader.py  
# 使用json.load()方法,读取json文件内容  
import json  
file_name = 'numbers.json'  
numbers = []  
with open(file_name, 'r') as f_obj:  
    numbers = json.load(f_obj)  
  
print(numbers)  

l  json.load()方法给定数据源对象,返回数据

3.   Demo,记住用户名字

写入配置文件

# remember_me.py  
import json  
username = input("What's your name? ")  
with open('username.json', 'w') as f_obj:  
    json.dump(username, f_obj)  
    print("We'll remember you when you come back, " + username + "!")  

从配置文件读取信息

# greet_user.py  
import json  
file_name = 'username.json'  
try:  
    with open(file_name, 'r') as f_obj:  
        username = json.load(f_obj)  
except FileNotFoundError:  
    print("The file " + file_name + " is not found.")  
else:  
    print("Hello, " + username + "!")  

合并到一个文件,查询是否有用户名配置文件,如果有,则打开,如果没有,则提示输入。

# remember_me.py  
import json  
  
file_name = 'username.json'  
try:  
    with open(file_name, 'r') as f_obj:  
        username = json.load(f_obj)  
except FileNotFoundError:  
    username = input("What's your name? ")  
    with open(file_name, 'w') as f_obj:  
        json.dump(username, f_obj)  
        print("We'll remember you when you come back, " + username + "!")  
else:  
    print("Hello, " + username + "!")  

4.   重构

把文件进行重新划分,形成更好的文件结构。

# greet_user.py  
import json  
  
def get_stored_user(file_name):  
    """ 
    获取文件中存储的文件名。 
    如果文件不存在,返回空。 
    """  
    try:  
        with open(file_name, 'r') as f_obj:  
            username = json.load(f_obj)  
    except FileNotFoundError:  
        return None  
    else:  
        return username  
  
def get_new_user(file_name):  
    """获取新的用户,存储到配置文件中"""  
    username = input("What's your name? ")  
    with open(file_name, 'w') as f_obj:  
        json.dump(username, f_obj)  
        print("We'll remember you when you come back, " + username.title() + "!"
)  
  
def greet_user(file_name):  
    """向配置文件里存储的用户问好"""  
    username = get_stored_user(file_name)  
    if username:  
        print("Hello, " + username.title() + "!")  
    else:  
        get_new_user(file_name)  
      
file_name = 'username.json'  
greet_user(file_name)  
划分为创建新用户、获得老用户、向用户问好三个模块。

————————————————————————————————————————————————

第一次尝试写博客,大家笑看即可。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值