import json

print("--------------- 读取文件-------------------")
# 关键字with 在不再需要访问文件后将其关闭,让Python负责妥善地打开和关闭文件
with open('pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents)
    # read() 到达文件末尾时返回一个空字符串,而将这个空字符串显示出来时就是一个空行。
    # 要删除多出来的空行,可在print 语句中使用rstrip()
    print(contents.rstrip())

print("--------------- 逐行读取-------------------")
with open('pi_digits.txt') as file_object:
    for line in file_object:
        # 每行的末尾都有一个看不见的换行符,而print 语句也会加上一个换行符,
        # 因此每行末尾都有两个换行符:一个来自文件,另一个来自print 语句。
        # print(line)
        print(line.rstrip())

print("--------------- 使用文件的内容-------------------")

with open('pi_digits.txt') as file_object:
    # readlines() 从文件中读取每一行,并将其存储在一个列表中
    lines = file_object.readlines()
pi_string = ''
for line in lines:
    pi_string += line.rstrip()
print(pi_string)
print(len(pi_string))

print("--------------- 写入文件-------------------")
# 读取模式 读 ('r' )、写入模式 写 ('w' )、附加模式 附 ('a' )
# 读取和写入文件的模式('r+' )
# 如果你要写入的文件不存在,函数open() 将自动创建它。
# 以写入('w' )模式打开文件,如果指定的文件已经存在,Python将在返回文件对象前清空该文件
with open('programming.txt', 'w') as file_object:
    file_object.write('i love programming.\n')
    file_object.write('l love creating new games.\n')
# 要给文件添加内容,而不是覆盖原有的内容,可以附加模式 打开文件
with open('programming.txt', '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')

print("--------------- 异常处理-------------------")
# 处理 ZeroDivisionError 异常
# 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: ")
#     try:
#         answer = int(first_number) / int(second_number)
#     except ZeroDivisionError:
#         print("You can't divide by 0!")
#     else:
#         print(answer)

# 处理 FileNotFoundError 异常
filename = 'alice.txt'
try:
    with open(filename) 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.")


# 失败时一声不吭
# 可在代码块中使用pass 语句来让Python 什么都不要做
def count_words(filename):
    """计算文件单词数目"""
    try:
        with open(filename) as f_obj:
            contents = f_obj.read()
    except FileNotFoundError:
        # 出现FileNotFoundError 异常时,将执行except 代码块中的代码,但什么都不会发生
        pass
    else:
        # 计算文件大致包含多少个单词
        words = contents.split()
        num_words = len(words)
        print("The file " + filename + " has about " + str(num_words) +
              " words.")


filenames = ['pi_digits.txt', 'aa.txt', 'programming.txt']
for filename in filenames:
    count_words(filename)

print("--------------- 存储数据-------------------")
# 使用 json.dump() 和json.load()
numbers = [2, 3, 5, 7, 11, 13]
with open("number.json", 'w') as f_obj:
    json.dump(numbers, f_obj)

with open("number.json") as f_obj:
    numbers = json.load(f_obj)
print(numbers)


# 如果以前存储了用户名,就加载它
# 否则,就提示用户输入用户名并存储它
def greet_user():
    """问候用户,并指出其名字"""
    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 come back, " + username + "!")
    else:
        print("Welcome back, " + username + "!")


greet_user()

 

posted on 2023-02-06 17:06  Zoie_ting  阅读(27)  评论(0编辑  收藏  举报