zoukankan      html  css  js  c++  java
  • Python 文件和异常

    一、从文件中读取数据

    #!/usr/bin/env python
    
    with open('pi') as file_object:
        contents = file_object.read()
        print(contents)
    
    
    ===================================
    3.1415926
      5212533
      2324255
    

    1、逐行读取

    #!/usr/bin/env python
    
    filename = 'pi'
    
    with open(filename) as file_object:
        for line in file_object:
            print(line)
    
    
    ===================================
    3.1415926
    
      5212533
    
      2324255
    
    #!/usr/bin/env python
    
    filename = 'pi'
    
    with open(filename) as file_object:
        for line in file_object:
            print(line.rstrip())
    
    ==================
    3.1415926
      5212533
      2324255
    

    2、创建一个包含文件各行内容的列表

    #!/usr/bin/env python
    
    filename = 'pi'
    
    with open(filename) as file_object:
        lines = file_object.readlines()     #readlines()方法是从文件中读取每一行,并将其存储在一个列表中
    
    for line in lines:
        print(line.rstrip())
    
    ==============================
    3.1415926
      5212533
      2324255
    

    3、使用文件内容

    #!/usr/bin/env python
    
    filename = 'pi'
    
    with open(filename) as file_object:
        lines = file_object.readlines()
    
    pi_string = ''
    for line in lines:
        pi_string += line.strip()
    
    print(pi_string)
    print(len(pi_string))
    
    ========================================
    3.141592652125332324255
    23
    

    二、写入文件

    1、写入空文件

    #!/usr/bin/env python
    
    filename = 'programming.txt'
    
    with open(filename,'w') as file_object:
        file_object.write("I love programming!")
    

    2、写入多行

    #!/usr/bin/env python
    
    filename = 'programming.txt'
    
    with open(filename,'w') as file_object:
        file_object.write("I love programming!
    ")
        file_object.write("yes!
    ")
    

    3、附加到文件

    #!/usr/bin/env python
    
    filename = 'pi'
    
    with open(filename,'a') as file_object:
        file_object.write("I love programming!
    ")
        file_object.write("yes!
    ")
    

    三、异常

    1、使用try-except代码块

    #!/usr/bin/env python
    
    try:
        print(5/0)
    except ZeroDivisionError:
        print("You cant divide by zero!")
    
  • 相关阅读:
    章节八、2-火狐的插件TryXPath
    章节八、1-如何使用火狐开发者工具来查找元素
    章节七、6-Map集合的区别
    章节七、5-Maps
    章节七、4-Sets
    章节七、3-ArrayList和LinkedList对比
    章节七、2-Linked List
    jQuery中$符号的作用
    jQuery基础的HTML与text区别
    推荐一些github上的免费好书
  • 原文地址:https://www.cnblogs.com/caicairui/p/7748380.html
Copyright © 2011-2022 走看看