2026/1/15 文件与报错

8 阅读7分钟

今天结合最近的血糖监测仪返回的数据&平时的用餐记录,做了对比分析,发现我的血糖不仅取决于当前时间的摄入,前几个小时的摄入同样对身体的摄入反馈机制造成影响,看来胖子真的不是一日之功,2026年的10斤任重而道远。 复习总结了类的笔记,并复习了文件与报错机制,笔记如下:

1. 读取文件

  • pathlib 模块,处理系统中的文件和目录
  • Path类,Path对象指向一个文件,可在使用文件前核实它是否存在,读取文件内容,将新数据写入文件。
  • VS Code会在最近打开的文件夹里查找文件,所以使用前需先打开程序所在文件夹。
  • read_text()在读取中,到达文件末尾时会返回一个空字符串,最终会被显示为一个空行,删除该空字符串,对变量调用rstrip(),即path.read_text().rstript(),被称为方法链式调用。

2. 相对文件路径和绝对文件路径

  • 相对文件路径:相对于当前运行的程序所在目录的指定位置 当所有文件存储在程序所处文件夹的下级子文件夹里时,相对路径表示:子文件夹名词/文件名词('text_files/filename.txt')

  • 绝对文件路径:文件在计算机中的准确位置,以系统的根文件夹为起点,很长。故简单做法为将文件存储在程序文件所在的目录中,或者存储在其目录下的一个子文件夹里。

  • 即使Windows系统使用==反斜杠(\)== 来显示路径,但在代码中,则需要使用 ==斜杠/==。

3.访问文件中的各行

  • 可以使用splitlines()方法将冗长的字符串转换为一系列行,再使用for循环以每次一行的方式检查各行: flie_reader.py
from pathlib import Path

path = Path('pi_digits.txt')
contents = path.read_txt()

lines=contents.splitlines()
for line in lines:
    print(line)

4.使用文件的内容

pi_string.py
    from pathlib import Path
    
    path = Path('pi_digits.txt')
    contents = path.read_txt()
    
    lines=contents.splitlines()
    pi_string = ''
    for line in lines:
        pi_string += line
    
    print(pi_string)
    print(len(pi_string))

5.写入文件

  • 定义文件的路径后,可使用write_text()将数据写入该文件中。若path变量对应的路径指向的文件不存在,会创建它 write_message.py
from pathlib import Path

path = Path('programming.txt')
path.write_text('I love programming.')

==注意:Python只能将字符串写入文本文件,如要将数值数据存储到文本文件中,先要str()。

  • 针对写入多行,可先创建一个字符串变量(包含全部内容),再将该变量传递给write_text()
  • 在对path对象调用write_text()方法时,必须谨慎,对指定文件使用该方法,会先删除其中的内容。

练习

  • 访客
name = input("Please input your name. ")
from pathlib import Path
path = Path('guest.txt')
path.write_text(name)
  • 访客簿
from pathlib import Path

path = Path('guest_book.txt')
print("Please input your name, if all of the names have done enter 'quit'. ")
all_names=[]
while True:
    name = input("Please input your name. ").strip()
    if name.lower() != 'quit':
        all_names.append(name)
    else:
        break

if all_names:
    name_text = '\n'.join(all_names)  
    path.write_text(name_text)
    print(f"\n已保存{len(all_names)} 个名字到 {path}")
    
    # 读取并显示内容
    print("\n文件内容:")
    print(path.read_text())

else:
    print("没有输出名字。")

6.处理错误

  • try_except-else代码块
--snip--
while True:
    --snip--
    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)

7.使用多个文件

  • word_count.py
from pathlib import Path

def count_words(path):
    """计算一个文件大致包含多少个单词"""
    try:
        contents = path.read_text(encoding='utf-8)
    except FileNotFoundError:
        print(f"Sorry,the file {path} does not exist.")
        # 也可以用pass 来静默失败
    else:
        # 计算文件大致包含多少个单词
        words = contents.split()
        num_words = len(words)
        print(f"The file {path} has about {num_words} words.")
filenames=['alice.txt','siddhartha.txt','moby_dick.txt']
for filename in filenames:
    path = Path(filename)
    count_words(path)

练习

  • 加法运算
print("We would do the plus with the two numbers you enter.")
first_num = input("Please enter number")
second_num = input("Please enter number")
try:
    plus = int(first_num) + int(second_num)
except ValueError:
    print("The contexts you enter are not all numbers,please make sure they are all numbers")
else:
    print(f"The numbers you enter are {int(first_num)} and {int(second_num)},the plus of them is {plus}.") 
  • 加法计算器
print("We would do the plus with the two numbers you enter,if you want to quit please enter 'quit'.")
#用户输入数字求和,如果输入的为非数,则提醒用户输入有误,重新执行循环,直到用户输入quit.
while True:
    first_num = input("Please enter the first number")
    if first_num == 'quit':
        break
    else:
        second_num = input("Please enter the second number")
        
    if second_num == 'quit':
        break
    else:
        try:
            plus = int(first_num) + int(second_num)
        except ValueError:
            print("The contexts you enter are not all numbers,please make sure they are all numbers")
        else: 
            print(f"The numbers you enter are {int(first_num)} and {int(second_num)},the plus of them is {plus}.") 

8.存储数据

  • 使用json.dumps(实参)来存储,返回一个字符串,json.loads(JSON格式字符串)来读取 number_writer.py
from pathlib import Path
import json

numbers=[2,3,4,5,6]

path = Path('numbers.json')
contents = json.dumps(numbers) #生成字符串
path.write_text(contents)
number_reader.py
from pathlib import Path
import json

path = Path('numbers.json')
contents = path.read_text()
numbers= json.loads(contents) #提取字符串,返回Python对象

print(numbers)
remember_me.py
from pathlib import Path
import json

path = Path('username.json')
if path.exists():
    contents=path.read_text()
    username=json.loads(contents)
    print(f"Welcome back, {username}!")
else:
    username = input("What is your name? ")
    contents = json.dumps(username)
    path.write_text(contents)
    print(f"We'll remember you when you come back,{username}!")

9.重构

将代码划分为一系列完成具体工作的函数来让其更清晰、易于理解、更容易扩展。
  • remember_me.py
from pathlib import Path
import json

def greet_user():
    """问候用户,并指出其名字"""
    path = Path('username.json')
    if path.exists():
        contents = path.read_text()
        username = json.loads(contents)
        print(f"Welcome back,{username}!")
    else:
        username = input("What is your name? ")
        contents = json.dumps(username)
        path.write_text(contents)
        print(f"We'll remember you when you come back,{username}!")

greet_user()

==上述将多个功能统一放在一个方法里,现在可以重构greet_user(),不让它执行这么多任务。==

from pathlib import Path
import json

def get_stored_username(path):
    """如果存储了用户名,就获取它"""
    if path.exists():
        contents = path.read_text()
        username = json.loads(contents)
        return username
    else:
        return None

        
def greet_user():
    """问候用户,并指出其名字"""
    path = Path('username.json')
    username = get_stored_username(path)
    if username:
        print(f"Welcome back,{username}!")
    else:
        username = input("What is your name? ")
        contents = json.dumps(username)
        path.write_text(contents)
        print(f"We'll remember you when you come back,{username}!")

greet_user()
from pathlib import Path
import json

def get_sorted username(path):
    """如果存储了用户名,就获取它"""
    --snip--

def get_new username(path):
    """提示用户输入用户名"""
    username = input("What is your name? ")
    contents = json.dumps(username)
    path.write_text(contents)
    return username

def greet_user():
    """问候用户,并指出其名字"""
    path = Path('username.json')
    username = get_sorted_username(path)
    if username:
        print(f"Welcome back, {username}!")
    else:
        username = get_new_username(path)
        print(f"We'll remember you when you come back, {username}!")

greet_user()

练习

  • 喜欢的数
from pathlib import Path
import json

path = Path('favorite_number')
number = input("What is your favorite number?")
number_in = json.dumps(number)
path.write_text(number_in)

#读取文件
path = Path('favorite_number')
number_in = path.read_text()
number=json.loads(number_in)
print(f"I know your favorite number!It's {number}.)
  • 记住喜欢的数
from pathlib import Path
import json

def get_sorted_number(path):
    """如果存储了,则获取存储的数"""
    if path.exists():
        comment = path.read_text()
        number = json.loads(comment)
        return number
        
    else:
        return None

def get_new_number(path):
    """如果没有数,则提升用户输入自己喜欢的数"""
    number = input("What is your favorite number? ")
    comment = json.dumps(number)
    path.write_text(comment)    
    return number

def print_number():
    """问候用户,并打印喜欢的数字"""
    path=Path('number.json')
    number = get_sorted_number(path)
    
    if number:
        print(f"Your favorite number is {number}!")
    
    else:
        number = get_new_number(path)
        print(f"Your favorite number is {number}!")

print_number()  
  • 用户字典
from pathlib import Path
import json

def get_sorted_information(path):
    """如果存储了,则获取存储的信息"""
    if path.exists():
        comment = path.read_text()
        information = json.loads(comment)
        return information
        
    else:
        return None

def get_new_information(path):
    """如果没有信息,则提升用户输入信息"""
    name = input("What is your favorite number? ")
    age = input("How old are you? ")
    city = input("Where do you live? ")
    information = {"Name" : name,"Age" : age,"City" : city}
    comment = json.dumps(information)
    path.write_text(comment)    
    return information

def print_information():
    """问候用户,并打印信息"""
    path=Path('information.json')
    information = get_sorted_information(path)
    
    if information:
        print("We got your information and would remember them!")
        print(f"Your information is {information}.")
    
    else:
        information = get_new_information(path)
        print("We got your information and would remember them!")
        print(f"Your information is {information}.")

print_information()  
  • 验证用户名
#验证用户名
from pathlib import Path
import json

def get_sorted_information(path):
    """如果存储了,则获取存储的信息"""
    if path.exists():
        comment = path.read_text()
        information = json.loads(comment)
        # print(information)
        return information
        
    else:
        return None

def get_new_information(path):
    """如果没有信息,则提升用户输入信息"""
    name = input("What is your name? ")
    age = input("How old are you? ")
    city = input("Where do you live? ")
    information = {"Name" : name,"Age" : age,"City" : city}
    comment = json.dumps(information)
    path.write_text(comment)    
    # print(information)
    return information

def print_information():
    """问候用户,并打印信息"""
    path=Path('information.json')
    information = get_sorted_information(path)
    
    if information:
        user_name = information['Name']
        print(f"The user_name now is {user_name},please check if it is write.")
        check = input("'Yes' for True,'No' for False.")
        if check =='Yes':
            print("We got your information and would remember them!")
        else:
            information = get_new_information(path)
            print("We got your information and would remember them!")
            print(f"Your information is {information}.")
    
    else:
        information = get_new_information(path)
        print("We got your information and would remember them!")
        print(f"Your information is {information}.")

print_information()