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. python ch10 文件异常

    2024-03-27 18:46:02       41 阅读
  2. 10-异常处理

    2024-03-27 18:46:02       49 阅读
  3. Python程序设计 文件异常 笔记整理

    2024-03-27 18:46:02       30 阅读
  4. 13.异常、IO流、序列化反序列化

    2024-03-27 18:46:02       23 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-27 18:46:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-27 18:46:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-27 18:46:02       82 阅读
  4. Python语言-面向对象

    2024-03-27 18:46:02       91 阅读

热门阅读

  1. node整理学习(三)

    2024-03-27 18:46:02       38 阅读
  2. 海思 Hi3403V100 简介

    2024-03-27 18:46:02       85 阅读
  3. Idea与DataGrip各版本通用破解码,无需脚本。

    2024-03-27 18:46:02       110 阅读
  4. 深入理解 LVS:配置与应用详解

    2024-03-27 18:46:02       46 阅读
  5. 单位里,永远要记住这些残忍的处事之道!

    2024-03-27 18:46:02       34 阅读
  6. Linux安装程序

    2024-03-27 18:46:02       43 阅读
  7. Linux UVC Gadget Driver开发

    2024-03-27 18:46:02       40 阅读
  8. c#委托案例

    2024-03-27 18:46:02       38 阅读
  9. SpringBoot-注解:@Async 使用

    2024-03-27 18:46:02       43 阅读
  10. springBoot实现热部署

    2024-03-27 18:46:02       30 阅读
  11. 排序问题HJ37 统计每个月兔子的总数

    2024-03-27 18:46:02       35 阅读