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

10 文件和异常

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

10 文件和异常

10.1 从文件中读取数据

10.1.1读取整个文件

要读取文件,需要一个包含几行文本的文件。首先创建一个文件。然后读取文件内容并输出

with open("pi_digits.txt") as file_object:
    contents = file_object.read()
print(contents)

关键字with在不在访问文件后将其关闭。相比open()与close(),使用with,我们只管打开文件,并在需要的时候使用它,不使用的时候则会自动关闭。

read()读取文件到达末尾时,会返回一个空字符串,而将这个空字符串显示出来时就是一个空行。

要删除多出来的空行,可在函数调用中使用retrip()

10.1.2文件路径

一般python将在当前执行的文件所在目录中去查找

但有的文件可能是存在于项目中的其他文件夹中,此时要指明文件的路径。

file_path = "/home/ehmatthes/other_files/text_files/filename.txt"

with open(file_path) as file_project:

10.1.3逐行读取

读取文件时,常常需要检查其中的每一行:

filename = "pi_digits.txt"
with open(filename) as file_object:
    for line in file_object:
        print(line)

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

使用关键字with时,open()返回的文件对象只在with代码块内可用。可将with代码块内将文件的各行存储在一个列表中,并在with代码块外使用该列表:

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

10.1.5使用文件的内容

将文件读取到内容中后,就能以任何方式使用这些数据了。

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)
print(len(pi_string))

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

对于一个数据很大的文件,这种方法同样可以读取,但以免终端因为显示全部而不断滚动,这里只打印小数点后面50位

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(f"{pi_string[:52]}...")
print(len(pi_string))

10.1.7圆周率中包含你的生日吗

for line in lines:
    pi_string += line_strip()
birthday = input("Enter your birthday,in the form mmddyy:")
if birthday in pi_string:
    print("Your birthday appears in the first million digits od pi!")
else:
    print("Your birthday does not appear in the first million digits of pi.")

10.2写入文件

10.2.1写入空文件

要将文本写入文件,你再调用open()时需要提供另一个实参,告诉python你要写入打开的文件

filename = "programming.txt"
with open(filename, "w") as file_object:
    file_object.write("I love programming.")

10.2.2写入多行

函数write()不会在写入的文本末尾添加换行符,因此如果写入多行时没有指定换行符,文件看起来可能不是你希望的那样。

filename = "programming.txt"
with open(filename, "w") as file_object:
    file_object.write("I love programming.n")
    file_object.write("I love creating new games.")

10.2.3附加到文件

如果要给文件添加内容,而不是覆盖所有的内容,可以用附加模式打开文件。

filename = "programming.txt"
with open(filename, "a") as file_object:
    file_object.write("I love programming.n")
    file_object.write("I love creating new games.n")

打开文件时制定了实参“a”,以便将内容附加到文件末尾,而不是覆盖原来的文件。

10.3异常

python使用称为异常的特殊对象来管理程序执行期间发生的错误。每当发生让python不知所措的错误时,它都会创建一个异常对象。

异常是使用try-except代码块来处理的。try-except代码块让python执行指定的操作,同时告诉python发生异常怎么办。

10.3.1处理ZeroDivisionError异常

print(5/0)

10.3.2使用try-except代码块

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

如果try代码块中的代码导致了错误,python将查找与之匹配的except代码块并运行其中的代码。

10.3.3使用异常避免崩溃

while True:
    first_number = input("nFirst number:")
    if first_number == "q":
        break
    second_number = input("nSecond number:")
    if second_number == "q":
        break
    answer = int(first_number) / int(second_number)
    print(answer)

执行除数为0可能会导致崩溃。避免崩溃:

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("nSecond 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)

10.3.5处理FileNotFoundError异常

查找的文件未知错误、文件名不正确、文件不存在。这些情形都可以使用try-except代码块来直观地处理。

filename = "alice.txt"
with open(filename, encoding="utf-8") as f:
    contents = f.read()    #文件没有存储在相应的目录中

捕捉异常

filename = "alice.txt"
try:
    with open(filename, encoding="utf-8") :
        contents = filename.read()
except FileNotFoundError:
    print("No such a file!")

10.3.6分析文本

使用split()方法,它能根据一个字符串创建一个单词列表

title = "Alice in Wonderland"
print(title.split())
filename = "alice.txt"
try:
    with open(filename, encoding="utf-8") :
        contents = filename.read()
except FileNotFoundError:
    print("No such a file!")
else:
    words = contents.split()
    new_words = len(words)
    print(f"The {filename} has about {new_words} words")

10.3.7使用多个文件

使用函数分析数据

def count_words(filename):
    try:
        with open(filename, encoding="utf-8") as f:
            contents =f.read()
    except FileNotFoundError:
        print("No such a file!")
    else:
        words = contents.split()
        new_words = len(words)
        print(f"The {filename} has about {new_words} words")
filename = "programming.txt"
count_words(filename)

将多个文件放到列表中,分别进行文件调用并实现扫描,展示文件不存在时应对得有多出色。

filenames = ["alice.txt", "little_man.txt", "siddhartha.txt", "moby_dick.txt"]
for filename in filenames:
    try:
        with open(filename, encoding="utf-8") as f:
            contents = f.read()
    except FileNotFoundError:
        print(f"The {filename} doesn't exist!")
    else:
        words = contents.split()
        new_words = len(words)
        peint(f"The {filename} has {new_words} words")

10.3.8静默失败

有时候你需要python运行程序发生异常时保持静默,我们可以通过except代码块让程序什么都不用做。可以使用pass语句让程序什么都不要做:

for filename in filenames:
    try:
        with open(filename, encoding="utf-8") as f:
            contents = f.read()
    except FileNotFoundError:
        pass                           # 什么都不要做
    else:
        words = contents.split()
        new_words = len(words)
        peint(f"The {filename} has {new_words} words")

10.4存储数据

一种简单的方式是使用模块json来存储数据

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

第一个程序使用json.dump()来存储这组数,第二个程序使用json.load()

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

numbers = [2, 3, 4, 6, 8, 5, 7]
filename = "number.json"
with open(filename, "w") as f:
    json.dump(numbers,f)

使用json.load()将列表读取到内存中

with open(filename) as f:
    numbers = json.load(f)
print(numbers)

10.4.2保存和读取用户生成的数据

实例:提示用户首次运行程序时输入自己的名字,并在再次运行程序时记住他。

存储用户的名字:

import json
username = input("What is your name?")
filename = "username.json"
with open(filename, "w") as f:
    json.dump(username, f)
    print(f"We'll remember you when you come back,{username}")

向已存储的名字的用户发出问候

with open(filename) as f:
    username = json.load(f)
    print(f"Welcome back,{username}")

程序合并,如果以前存储了用户名,就加载它,否则提示用户输入用户名并存储它

import json
filename = "username.json"
try:
    with open(filename) as f:
        username = json.load(f)
except FileNotFoundError:
    username = input("What is your name?")
    with open(filename, "w") as f:
        json.dump(username,f)
        print(f"We'll remember you when you come back,{username}")
else:
    print(f"Welcome back,{username}")

10.4.3重构

在代码能够正确运行的基础上,通过将其划分为一系列完成具体工作的函数,还可以改进。这样的过程叫做重构

import json
filename = "username.json"
def greet_user():
    try:
        with open(filename) as f:
            username = json.load(f)
    except FileNotFoundError:
        username = input("What is your name?")
        with open(filename, "w") as f:
            json.dump(username, f)
            print(f"We'll remember you when you come back,{username}")
    else:
        print(f"Welcome back,{username}")
greet_user()

重构:

import json
def get_stored_username():
    filename = "username.json"
    try:
        with open(filename) as f:
            username = json.load(f)
    except FileNotFoundError:
        return None
    else:
        return username
def greet_user():
    username = get_stored_username()
    if username:
        print(f"Welcome back.{username}")
    else:
        username = input("What is your name?")
        filename = "username.json"
        with open(filename, "w") as f:
            json.dump(username, f)
            print(f"We'll remember you when you come back,{username}")
greet_user()

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

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

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