Python文件与异常 学习笔记

"""文件路径"""

# 相对文件路径(适用于打开位于不同文件夹的文件)
with open(r'1\temp.py') as file_object:
    # 运用方法read读取整个文件
    contents = file_object.read()
    print(contents.strip(), end='')


# 绝对文件路径(完整路径,任何位置,较麻烦)
file_path = r'C:\Users\user\Desktop\pi_digits.txt'
with open(file_path) as file_object:
    contents = file_object.read()
    print(contents.strip(), end='')


# 以每次一行的方式检查(遍历)文件
filename = 'pi_digits.txt'
with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())


# 创建包含文件各行内容的列表,便于在with之外使用文件内容
filename = 'pi_digits.txt'
with open(filename) as file_object:
    # 方法readlines()从文件中读取每一行,并将其存储在一个列表中
    lines = file_object.readlines()
for line in lines:
    print(line.rstrip())




"""文件处理"""

filename = 'guest.txt'
""" 
默认(只读模式),
'r'(读取), 'w'(写入)->会覆盖原有内容,
'a'(附加), 'r+'(读取和写入)
"""
with open(filename, 'a') as file_object:
    # 运用方法write将字符串导入文件
    file_object.write('i love programming')


# 用try-except代码块处理异常,可避免出现traceback(错误消息与追溯)
try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero")


# 通过try-except后的代码可通过else执行,即try-except-else代码块
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
    first = input('\nFirst number is: ')
    if first == 'q':
        break
    second = input('Second number is: ')
    if second == 'q':
        break
    try:
        answer = int(first) / int(second)
    # 进行到except时程序不会终止
    except ZeroDivisionError:
        print("You can't divide zero.")
    else:
        print(answer)


"""处理单个文件FileNotFoundError(文件不存在)异常"""
filename = 'alice.txt'
# 异常起始点在open,因此try在open之前
try:
    with open(filename) as file_object:
        contents = file_object.read()
except FileNotFoundError:
    msg = "Sorry, the file " + filename + " doesn't exist."
    print(msg)
else:
    # 用split分割字符串,并存储到列表中
    words = contents.split()
    num_word = len(words)
    print(num_word)


def count_num(filename):
    """计算一个文件中包含多少单词"""
    try:
        with open(filename) as file_object:
            contents = file_object.read()
    except FileNotFoundError:
        msg = "Sorry, the file " + filename + " doesn't exist."
        print(msg)
    else:
        # 用split分割字符串,并存储到列表中
        words = contents.split()
        num_word = len(words)
        print(num_word)
        

# 简单使用pass,出措时不做提示
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
    count_num(filename)

def count_num(filename):
    """计算一个文件中包含多少单词"""
    try:
        --snip--
    except FileNotFoundError:
        # 运用pass可以在程序出错时 ‘一声不吭’
        pass
    else:
        --snip--
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
    count_num(filename)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值