Day 8 python 从入门到实践——文件与异常

  • 读取整个文件
with open("pi_digits.txt") as file_object: #此处pi_digits.txt文件位于正在编辑的py文件同目录文件夹内
    contents = file_object.read()
    print(contents.rstrip())
  • 简单使用读取文件
#文件路径
#相对路径
# with open(r'text_files\file_name.txt') as file_object: #此处text_file为正在编写的py文件所在目录的子目录文件夹
#绝对路径
#with open(r'C:\User\ehamatthes\other_files\text_file\file_name.txt') as object : #此处为计算机内目标文件的完整路径

#逐行读取
file_name = 'pi_digits.txt'
with open(file_name) as file_object:
    for line in file_object:
        print(line.rstrip())#此处方法rstrip()消除每行末尾的换行符
        
#将文件各行存储到列表中
with open(file_name) as file_object:
    lines = file_object.readlines() #readlines()方法按行读取文件中每一行,并储存到一个列表中
for line in lines:
    print(line.rstrip())

#简单使用文件内容
with open(file_name) as file_object:
    lines = file_object.readlines()
pi_string = ''
for line in lines:
    pi_string+= line.strip()
print("\n"+pi_string)
print(len(pi_string))

#读入大型文件内容
file_name = 'pi_million_digits.txt'
with open(file_name) as file_object:
    lines = file_object.readlines()
pi_string = ''
for line in lines :
    pi_string+= line.strip()
print(pi_string[:52]+"...")
print(len(pi_string))
print(len(pi_string[:52]))
  • 将输出写入到空文件
file_name = "programming.txt"
with open(file_name,"w") as file_object: #open()中第二个实参指定python以何种方式打开文件——'w'-写入模式;'a'-附加模式;'r+'-读取与写入;'r'-读取模式;默认为只读
    file_object.write('I love python')
  • 写入多行
with open(file_name,'w') as file_object:
    file_object.write("I love creating new gammes!\n")
    file_object.write("I love the world!\n")
#write()方法不会在写入的字符后加入换行符
  • 将内容附加到文件末尾
with open(file_name,"a") as file_object: #'a'-附加模式
    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')
  • 异常
#ZeroDivisionError异常——异常为python中一种特殊对象
try:    #try: 后代码块发生错误则执行except  :后代码块
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")

#使用异常避免崩溃
print('Give me two numbers, and I will divide them.')
print("Enter 'q' to quit !")
while True:
    first_num =input("\nFirst number: ")
    if first_num == "q":
        break
    second_num = input("Second number: ")
    if second_num == "q":
        break
    try:
        answer = int(first_num) / int(second_num)
    except ZeroDivisionError:
        print("You can't divide by 0!")
    else:
        print(answer) #else: 块放置try: 块代码成功运行后执行的代码

#FileNotFoundError异常
file_name = 'alice.txt' #此处alice.txt文件不存在py文件同目录下
try:
    with open(file_name) as f_obj:
        contents = f_obj.read()
except FileNotFoundError:
        msg = 'Sorry , the file '+file_name+' does not exsit.'
        print(msg)
else:
    words = contents.split() #split()方法根据字符串创建列表,默认以空格为分隔符
    num_words = len(words)
    print('The file '+file_name+' has about '+str(num_words)+' words.')

#使用多个文件
def count_words(file_name):
    """计算一个文件包含多少单词"""
    try:
        with open(file_name) as f_obj:
            contents = f_obj.read()
    except FileNotFoundError:
            msg = 'Sorry , the file '+file_name+' does not exsit.'
            print(msg)
    else:
            words = contents.split()
            num_words = len(words)
            print('The file '+file_name+' has about '+str(num_words)+" words")
file_names = ['alice.txt', 'siddhartha.txt', 'moby_dict.txt', 'little_women.txt']
for file_name in file_names:
    count_words(file_name)

#出现异常时一声不吭
def count_words(file_name):
    """计算一个文件包含多少单词"""
    try:
        with open(file_name) as f_obj:
            contents = f_obj.read()
    except FileNotFoundError:
        pass
    else:
        words = contents.split()
        num_words = len(words)
        print('The file '+file_name+' has about '+str(num_words)+" words")
file_names = ['alice.txt', 'siddhartha.txt', 'moby_dict.txt', 'little_women.txt']
for file_name in file_names:
    count_words(file_name)
  • 使用json模块方法存储数据
#写入
import json
numbers = list(range(1,10,2))
file_name = 'numbers.json'
with open(file_name,'w') as f_obj:
    json.dump(numbers,f_obj) #json.dump()函数接受两个实参,一个为存储的数据,一个为存储数据的文件对象实参
    
#读取
file_name = 'numbers.json'
with open(file_name) as f_obj:
    numbers = json.load(f_obj) #json.load()函数接受文件对象实参
print(numbers)

#保存与读取用户生成的名字
import json
# 如果以前存储了用户名,就加载
# 否则,就提示用户输入
file_name = 'username.json'
try:
    with open(file_name) as f_obj:
        user_name = json.load(f_obj)
except FileNotFoundError:
        user_name = input("What is your name? ")
        with open(file_name, 'w') as f_obj:
            json.dump(user_name, f_obj)
            print('We will remember you when you come back!'+user_name.title()+' !')
else:
        print('Welcome back, '+user_name.title()+" !")

#重构——将代码划分为一系列完成具体工作的函数
import json
def get_stored_username():
    """如果储存了用户名,就返回它,否则返回None"""
    file_name = "user_name.json"
    try:
        with open(file_name) as f_obj:
            user_name = json.load(f_obj)
    except FileNotFoundError:
        return None
    else:
        return user_name

def get_new_username():
    """提示用户输入用户名"""
    user_name = input("What is your name? ")
    file_name = 'user_name.json'
    with open(file_name, 'w') as f_obj:
        json.dump(user_name,f_obj)
    return user_name

def greet_user():
    """问候用户,指出名字"""
    user_name = get_stored_username()
    if user_name:
        print('Welcome back, '+user_name+' !')
    else:
        user_name = get_new_username()
        print('We will remember you when you come back! '+user_name+' !')

greet_user()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值