美文网首页
Python入门之文件和异常

Python入门之文件和异常

作者: 我的袜子都是洞 | 来源:发表于2019-07-17 20:39 被阅读0次

文件

从文件中读取数据

读取整个文件

创建一个文件pi_digits.txt

3.141592653589793238462643383279

下面程序打开读取这个文件,再将其显示到屏幕上

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

函数open()接受一个参数:要打开文件的名称。
关键字with保证在不需要访问文件后将其关闭。让Python去确定何时关闭文件。

逐行读取

每次一行的方式检查文件,可对文件对象使用for循环。

file_name = 'pi_digits.txt'

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

每行末尾都有空白行,可以使用rstrip()消除:

file_name = 'pi_digits.txt'

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

写入文件

保存数据最简单的方式之一是将其写入到文件中。

写入空文件

file_name = 'programming.txt'

with open(file_name, 'w') as file_object:
    file_object.write("I love you")

文件写入模式:

  • w:写入模式
  • a:附加模式
  • r:读取模式

异常

异常是使用try-except块处理的。

处理ZeroDivisionError异常

try:
    print(5/0)
except ZeroDivisionError:
    print("兄弟,不能除0")

使用异常避免崩溃

发生错误时,如果程序还有工作没有完成,妥善的处理错误就尤其重要。

while True:
    first_number = input("\nFirst number: ")
    if file_name == 'q':
        break
    second_number = input("Second number: ")
    try:
        answer = int(first_number) / int(second_number)
    except ZeroDivisionError:
        print("兄弟,不能除0啊")
    else:
        print(answer)

except代码块告诉Python,出现ZeroDivisionError异常时该怎么办。如果除法运算成功,我们就使用else代码块打印结果。

处理FileNotFoundError异常

filename = 'alice.txt'

try:
    with open(filename) as file_object:
        contents = file_object.read()
except FileNotFoundError:
    msg = "对不起,文件" + filename + "不存在"
    print(msg)

储存数据

模块json让你能够将简单的Python数据结构转储到文件中,并在程序在此再次运行时夹在该文件中的数据。

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

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

import json

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

filename = 'number.json'
with open(filename, 'w') as file_object:
    json.dump(numbers, file_object)

使用json.load()将文件读取到内存中:

import json

filename = 'number.json'
with open(filename) as file_object:
    numbers = json.load(file_object)
print(numbers)

相关文章

网友评论

      本文标题:Python入门之文件和异常

      本文链接:https://www.haomeiwen.com/subject/wrzclctx.html