栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python入门(三)——文件和异常

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python入门(三)——文件和异常

10 文件和异常

异常是Python创建的特殊对象,用于管理程序运行时出现的错误
模块 json,能够保存用户数据,以免在程序停止运行后丢失

10.1 从文件中读取数据

要使用文本文件中的信息,首先需要将信息读取到内存中

10.1.1读取整个文件

创建一个文件:pi_digits.txt

3.1415926535
  8979323846
  2643383279

下面这个程序打开并读取这个文件,再将其内容显示到屏幕上
要以任何方式使用文件,都要先打开文件,函数 open() 接受一个参数:要打开的文件的名称,Python在当前执行的文件所在目录中查找指定的文件
函数 open() 返回一个表示文件的对象,Python将这个对象存储在我们将在后面使用的变量中
关键字 with 在不需要访问文件后将其关闭
调用了 open() 但没有调用 close(),只管打开文件,Python会自己将其关闭
使用方法 read() 读取这个文件的全部内容,read() 到达文件末尾是返回一个空字符串表现为一个空行,要删除这个空行可在 print 语句中使用 rstrip():

with open('pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents.rstrip())
10.1.2 文件路径

根据组织文件的方式,有时可能要打开不在程序文件所属目录中的文件,Python不会在其子文件夹中查找
要让Python打开不与程序文件位于同一个目录中的文件,需要提供文件路径

使用相对文件路径
with open('text_filesfilename.txt') as file_object:
使用绝对文件路径

通过使用绝对路径,可读取系统任何地方的文件

file_path = r'C:Usersehmatthesother_filesfilename.txt'
with open(file_path) as file_object

file_path = r'H:poetry_1.txt'

with open(file_path, encoding='utf-8') as file_object:

    contents = file_object.read()
    print(contents)
10.1.3 逐行读取

读取文件时,常常需要检查其中的每一行,要以每次一行的方式检查文件,可对文件对象使用 for 循环

filename = 'pi_digits.txt'

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

如果不加上 rstrip() 会出现空行,因为在文件中,每行的末尾都有一个看不见的换行符,而 print 语句也会加上一个换行符,因此每行末尾都有两个换行符,一个来自文件另一个来自 print 语句

10.1.4 创建一个包含文件各行内容的列表

使用关键字 with 时,open() 返回的文件对象是在 with 代码块内可用,如果要在 with 代码块外访问文件的内容,可在 with 代码块内将文件的各行存储在一个列表中,并在 with 代码块外使用该列表
readlines() 从文件中读取每一行,并将其存储在一个列表中

file_name = 'pi_digits.txt'

with open(file_name) as file_object:
    lines = file_object.readlines()

for line in lines:
    print(line.rstrip())
10.1.5 使用文件的内容

创建一个字符串,包含文件中存储的所有数字,且没有任何空格

file_name = 'pi_digits.txt'

with open(file_name) as file_object:
    lines = file_object.readlines()

pi_string = ''
for line in lines:
    pi_string += line.strip()

print(pi_string)
print(len(pi_string))

读取文本文件时,Python将其中所有的文本都解读为字符串,如果读取的数字必须使用函数 int() 或 float() 将其转换为数字

10.1.6 包含一百万位的大型文件

对于你可以处理的数据量,Python没有任何限制,只要系统的内存足够多,想处理多少数据都可以

file_name = 'pi_million_digits.txt'

with open(file_name, encoding='utf-8') as file_object:
    lines = file_object.readlines()

pi_string = ''
for line in lines:
    pi_string += line.strip()

birthday = input("Enter your birthday, in the from mmddyy: ")
if birthday in pi_string:
    print("Your birthday appears in the first million digits of pi!")
else:
    print("Your birthday appears in the first million digits of pi!")
10.2 写入文件

通过将输出写入文件,即使关闭包含程序输出的终端窗口,这些输出也依然存在

10.2.1写入空文件

要将文本写入空文件,在调用 open() 是需要提供另一个实参,告诉Python你要写入打开的文件
打开文件时,科之低昂读取模式(‘r’)、写入模式(‘w’)、附加模式(‘a’)或让你能够读取和写入文件的模式(‘r+’),如果省略模式实参Python将以默认的只读模式打开文件
如果你要写入的文件不存在,函数 open() 将自动创建它
以写入模式(‘w’)打开文件时要小心,如果指定的文件已经存在,Python将在返回文件对象前清空该文件
使用文件方法 write() 将一个字符串写入文件,Python只能将字符串写入文本文件,要将数值数据存储到文本文件中,必须先使用函数 str() 将其转换为字符串格式

file_name = 'programming.txt'

with open(file_name, 'w', encoding='utf-8') as file_object:
    file_object.write("I love programming.")
10.2.2 写入多行

函数 write() 不会再比写入的文本末尾添加换行符,要让每个字符串都单独占一行,需要在 write() 语句中包含换行符
像显示到终端的输出一样,还可以使用空格、制表符和空行来设置这些输出的格式

file_name = 'programming.txt'

with open(file_name, 'w') as file_object:
    file_object.write("I love programming.n")
    file_object.write("I love creating new games.n")
10.2.3 附加到文件

如果你要给文件添加内容而不是覆盖原有的内容,可以附加模式打开文件,此时Python不会在返回文件对象前清空文件,而你写入到文件的行都将添加到文件末尾,如果指定文件不存在,Python将为你创建一个空文件

file_name = 'programming.txt'

with open(file_name, 'a') as file_object:
    file_object.write("I also love finding meaning in large datasets.n")
    file_object.write("I love creating apps that can run in a browser.n")
10.3 异常

Python使用被称为异常的特殊对象来管理程序执行期间发生的错误,每当发生让Python不知所措的错误是,它都会创建一个异常对象,如果你编写了处理该异常的代码程序将继续运行,如果你未对异常进行处理,程序将停止并显示一个traceback,其中包含有关异常的报告
异常是使用 try-except 代码块处理的

10.3.2 使用 try-except 代码块
try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")
10.3.4 else 代码块

通过将可能引发错误的代码放在 try-except 代码块中,可提高这个程序抵御错误的能力

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 = int(first_number) / int(second_number)
    except ZeroDivisionError:
        print("You can't divide by 0!")
    else:
        print(answer)
file_name = 'alice.txt'

try:
    with open(file_name, 'r', encoding='utf-8') as f_obj:
        contents = f_obj.read()
except FileNotFoundError:
    msg = "Sorry, the file " + file_name + " does not exist."
    print(msg)
10.3.6 分析文本

方法 split() 以 空格为分隔符将字符串拆分成多个部分,并将这些部分都存储到一个列表中
指出文件 poetr_1.txt 中包含多少个单词

try:
    with open('H:poetry_1.txt', 'r', encoding='utf-8') as f_obj:
        contents = f_obj.read()
except FileNotFoundError:
    msg = "Sorry, the file does not exist."
    print(msg)
else:
    words = contents.split()
    num_words = len(words)
    print("The file has about " + str(num_words) + " words.")
10.3.7 使用多个文件
def count_words(filename):
    """计算一个文件大致包含多少个单词"""
    try:
        with open(filename, 'r', 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.")

file_name = 'poetry_1.txt'
count_words(file_name)

poetry_4.txt 不存在,但是不会影响这个程序处理其他文件

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

filenames = ['poetry_1.txt', 'poetry_2.txt', 'poetry_3.txt', 'poetry_4.txt']
for filename in filenames:
    count_words(filename)
10.3.8 失败时一声不吭

让程序在发生异常时一声不吭,像是设么都没有发生一样运行,正常编写 try 但是在 expect 中使用 pass 语句
pass 语句还充当占位符,提醒你在程序的某个地方什么都没有做,并且依旧也许要在这里做些什么

def count_words(filename):
    --snip--
    except FileNotFoundError:
        pass
    else:
        --snip--

filenames = ['poetry_1.txt', 'poetry_2.txt', 'poetry_3.txt', 'poetry_4.txt']
for filename in filenames:
    count_words(filename)
10.4 存储数据

使用模块 json 来存储数据,让你能够将简单的Python数据结构转储到文件中,并在程序再次运行时加载该文件中的数据
还可以使用json在Python程序之间分享数据,JSON数据格式并非Python专用的

10.4.1 使用 json.dump() 和 json.load() 函数 json.dump() 接受两个实参:要存储的数据以及可用于存储数据的文件对象
import json

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

filename = 'number.json'
with open(filename, 'w', encoding='utf-8') as f_obj:
    json.dump(numbers, f_obj)
函数 json.load() 将这个列表读取到内存中
import json

filename = 'number.json'
with open(filename, 'r', encoding='utf-8') as f_obj:
    numbers = json.load(f_obj)

print(numbers)
10.4.2 保存和读取用户生成数据

对于用户生成的数据,用json保存他们大有裨益,如果不以某种方式进行存储,等程序停止运行时用户的信息将丢失
rememb_me.py:存储用户的名字

import json

username = input("What is your name? ")

filename = 'username.json'
with open(filename, 'w', encoding='utf-8') as f_obj:
    json.dump(username, f_obj)
    print("We'll remember you when you come back " + username + "!")

greet_user.py:向其名字被存储的用户发出问候

import json

filename = 'username.json'
with open(filename, 'r', encoding='utf-8') as f_obj:
    username = json.load(f_obj)
    print("Welcome back, " + username + "!")

将上面两个程序合并成为一个程序

import json

# 如果以前存储了用户名就加载它
# 否则,就提示用户输入用户名并存储它
filename = 'username.json'
try:
    with open(filename, 'r', encoding='utf-8') as f_obj:
        username = json.load(f_obj)
except FileNotFoundError:
    username = input("What is your name? ")
    with open(filename, 'w', encoding='utf-8') 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 重构

代码能够正常的运行,但是可做进一步改进——将代码划分为一系列完成具体工作的函数,这样的过程成为重构
重构让代码更清晰、更易于理解、更容易扩展
重构前:

import json

def greet_user():
    """问候用户,并指出其名字"""
    filename = 'username.json'
    try:
        with open(filename, 'r', encoding='utf-8') as f_obj:
            username = json.load(f_obj)
    except FileNotFoundError:
        username = input("What is your name? ")
        with open(filename, 'w', encoding='utf-8') as f_obj:
            json.dump(username, f_obj)
            print("We'll remember you when you come back, " + username + "!")
    else:
        print("Welcome back, " + username + "!")

greet_user()

重构后:

import json

def get_stored_username():
    """如果存储了用户名,就获取它"""
    filename = 'username.json'
    try:
        with open(filename, 'r', encoding='utf-8') 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 = 'username.json'
        with open(filename, 'w', encoding='utf-8') as f_obj:
            json.dump(username, f_obj)
            print("We'll remember you when you come back, " + username + "!")

greet_user()
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/283674.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号