美文网首页
第10章 文件和异常

第10章 文件和异常

作者: lkj666 | 来源:发表于2021-04-22 22:12 被阅读0次

参考书籍:《Python编程 从入门到实践》

1. 从文件中读取数据

1.1 一次性读取文件全部内容

#file_reader.py
with open('pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents.rstrip())
  1. 无论以何种方式使用文件,第一步都是先打开文件。
  2. 方法read()可读取文件的全部内容。
  3. read()在读取到文件末尾时会返回一个空字符串,表现为一个空行,可用rstrip()去除。
  4. 程序会在*.py程序文件所在目录查找相应的文件,也可以使用路径标明位置。

1.2 逐行读取文件内容

#file_reader.py
filename = 'pi_digits.txt'

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

1.3 在with代码块以外访问文件内容

filename = 'pi_digits.txt'

with open(filename) as file_object:
    lines = file.object.readlines()

for line in lines:
    print(line.rstrip())
  1. 将文件各行存储在一个列表中。
  2. 方法readlines():将文件中读取每一行,并将其存储在一个列表中。

1.4 使用文件的内容

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)
print(len(pi_string))
  1. strip():去除字符串前后空白。
  2. len():计算字符串长度。
  3. 读取的文件,所有文本都默认为字符串。若要将其当作数字使用,需要用函数int()float()转换为整数或浮点数。



2. 写入文件

#write_message.py
filename = 'programming'

with open(filename, 'w') as file_object:
    file_object.write("I love programming.\n")
    file_object.write("I love creating new games.\n")
  1. open()函数接两个参数,第一个提供要打开的文件名称;第二提供模式。
  2. w:写入模式
    r:读取模式(默认是只读文件)
    a:附加模式
    r+:读取和写入模式
  3. 若文件不存在,Python会自动创建文件。
  4. Python只能将字符串写入文本文件,要写入数值,需要用str()将数字转换为字符串。



3. 异常

3.1 处理ZeroDivisionError异常

print("Give me two numers, 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)
  1. try-except代码块,当执行try代码块出错时,执行except代码块。
  2. except代码块中,可以用pass告诉程序,即使程序出错,也可以什么都不显示。
  3. else代码块中,try代码块成功执行时,才会执行。

3.2 处理FileNotFoundError异常

def count_words(filename):
    """计算一个文件大致包含多少个单词"""
    try:
        with open(filename) as f_obj:
            contents = j_obj.read()
    except FileNotFoundError:
        msg = "Sorry, the file " + filename +" does not exist."
        print(msg)
    else:
        #计算文件大致包含多少个单词
        words = contents.spllit()
        num_words = len(words)
        print("The file " + filename + " has about " + str(num_words) + " words.")

filename = 'alice.txt'
count_words(filename)

filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
    count_words(filename)
  1. 方法split()以空格为分隔符将字符串分拆成多个部分,并将这些部分存储在一个列表中。



4. 存储数据

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

import json

filename = 'username.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 comm back, " + username + "!")
else:
    print("Welcome back, " + username + "!")

json.dump()json.load()用于存储和加载数据对象。
json.dump()接两个参数:要存储的数据+可用于存储数据的文件对象。

4.1 重构程序

import json

def get_stored_useranme():
    """如果存储了用户名,就获取它"""
    filename = 'username.json'
    try:
        with open(filenam) 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("Welcom back, " + username + "!")
    else:
        username = input("What is your name?")
        filename = 'username.json'
        with open(username, 'w') as f_obj:
            json.dump(username, f_obj)
            print("We'll remember you when you come back, " + username + "!")

greet_user()

程序重构的目的是让逻辑更加清晰,每个函数都执行一个任务

相关文章

  • Python学习5

    第10章 文件和异常 处理异常和文件,你在本章学习的技能可提高程序的适用性、可用性和稳定性。 10.1 从文件中读...

  • 第10章 文件和异常

    参考书籍:《Python编程 从入门到实践》 1. 从文件中读取数据 1.1 一次性读取文件全部内容 无论以何种方...

  • 文件和异常

    打开文件 with关键词可以在不使用文件时自动关闭文件.open('pi_digits.txt')返回了一个对象,...

  • 文件和异常处理

    文件 在Python之中读写一个文件我们使用它的内置函数open来进行操作。 写读写文件如下: 读文件时需要注意的...

  • 十九、文件和异常

    文件和异常 至此,已经掌握了编写组织有序而易于使用的程序所需的基本技能,该考虑让程序目标更明确、用途更大了。 本章...

  • python文件和异常

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

  • Python——文件和异常

    从文件中读取数据 使用文本文件中的信息,首先需要将信息读取到内存中。可以选择一次性读取文件的全部内容,也可以选择逐...

  • Python:文件和异常

    从文件中读取数据 读取整个文件 函数open()接受一个文件名作为参数,将文件内容存储在as后面指定的对象中。使用...

  • Python文件和异常

    文件读取 写入文件 异常处理 存储数据的实例 1、从文件中读取数据 file_reader.py open() 打...

  • 11-3学习总结

    今天学习了第9章异常处理: 1.异常:程序在执行过程中发生的错误。 常见的异常: 文件找不到、文件操作权限不足、网...

网友评论

      本文标题:第10章 文件和异常

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