python ch10 文件和异常

文件

# file tyr except
# 所在的目录中查找pi_digits.txt
# 关键字with在不再需要访问文件后将其关闭
# 1 读取文件
filename = 'pi_digitis.txt'
with open(filename) as file_object:
    contents = file_object.read()
    print(contents)

print("")
with open(filename) as file_object:
    lines = file_object.readlines()
    for line in lines:
        print(line.rstrip())

    #使用文件中得内容
    pi_string = ''
    pi_string_1 = ''
    for line in lines:
        pi_string += line.rstrip()
        pi_string_1 += line.strip()
print(pi_string)
print(len(pi_string))
print(pi_string_1)
print(len(pi_string_1))

# 2 写入文件
filename = 'programming.txt'
# 打开文件时,可指定读取模
#  式('r')、写入模式('w')、附加模式('a')或让你能够读取和写入文件的模式('r+')。如果
#  你省略了模式实参,Python将以默认的只读模式打开文件
with open(filename, 'w') as file_object:
    file_object.write("I love programming.")
    file_object.write("I love creating new games.")
    file_object.write("\n ")
    file_object.write("I love programming.\n")
    file_object.write("I love creating new games.\n")

#    附件
with open(filename, '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")


异常

# try except

#处理ZeroDivisionError异常的try-except
try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")
# try-except代码块后面还有其他代码,程序将接着运行,因为已经告诉了Python如何处
#  理这种错误。

# # 依赖于try代码块成功执行的代码都应放到else代码块
# 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 异常
print("")
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)

#  Python有一个pass语句,可在代码块中使用它来让Python什么都不要做
print("")
def count_words(filename):
    """计算一个文件大致包含多少个单词"""
    try:
        with open(filename) as f_obj:
            contents = f_obj.read()
    except FileNotFoundError:
        # msg = "Sorry, the file " + filename + " does not exist."
        # print(msg)
        pass
    else:
        # 计算文件大致包含多少个单词
        words = contents.split()
        num_words = len(words)
        print("The file " + filename + " has about " + str(num_words) +
        " words.")
filename = 'alice.txt'
count_words(filename)


# 使用json.dump()来存储这组数字,而第二个程序将使用json.load()。
import json
numbers = [2,3,4,5,6,7,8,9]
filename = 'numbers.json'
with open(filename,'w') as f_obj:
    json.dump(numbers,f_obj)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值