您的位置:首页 > 编程语言 > Python开发

Python学习笔记 Day11 文件和异常

2018-12-11 20:29 295 查看

Day 11 文件和异常

  • 从文件读取数据 一次性读取全部文件内容
    with open('pi_digits.txt') as file_object:
    contents =file_object.read()
    函数open()用于打开文件,参数位文件名,返回值位文件对象;
  • 关键字with在不需要访问文件后自动完成关闭工作;
  • 逐行读取
    file_name = "pi_digits.txt"
    with open(file_name) as file_object:
    for line in file_object:
    print (line.rstrip())
      从输出结果看,open返回的file_object应该是一个列表类型的变量;
    • 关键字with结合open()返回的文件对象只在with代码块内可见,如需在with代码块外可见,则需创建一个列表对象,用于存储文件各行内容并留着在with代码块外使用;
      with open(file_name) as file_object:
      lines = file_object.readlines()
      for line in lines:
      print (line.rstrip())
  • 使用文件内容
  • 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.rstrip()
    print (pi_string)
    print (len(pi_string))
  • 写入文件
      with open(filename, ‘w’) as file_object:
    filename = 'programming.txt'
    with open(filename, 'w') as file_object:
    file_object.write("I love programming!")
    • open的第二个实参: ‘r’:只读模式打开
    • ’w’:写入模式打开
    • ‘a’:附加模式打开
    • ’r+‘:读取和写入模式打开
    • 默认以只读方式打开文件。
  • 异常
      python程序执行过程中发生错误是,会产生一个异常对象,如果编写了处理该异常的代码,程序继续运行,否则,程序将停止,并显示一个traceback。
    • try expect else 代码块用于处理异常
    try:
    answer = int(first_number) / int(second_number)
    except ZeroDivisionError:
    print("You can't divide bu 0!")
    else:
    print(answer)
  • 分析文本
    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.")
  • 同时处理多个文件:将需要处理的文件名用列表存储
  • #定义计算文件有多少个单词的函数
    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)
    else:
    #计算文件大致包含多少个单词
    words = contents.split()
    num_words = len(words)
    print("The file " + filename + " has about " +
    str(num_words) + " words.")
    
    filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt',
    'little_women.txt']
    
    for filename in filenames:
    count_words(filename)
    内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
    标签: