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!")
    
  • 相关阅读:
    浏览器兼容性优化
    js操作table(增加行,删除行,上移,下移,复制行)
    褚时健传读后感
    新鞋
    八达岭奥莱
    springMVC 多方法controller
    springMVC入门配置及helloworld实例
    springMVC源码下载地址
    spring3mvc与struts2比较
    hql语句拼接的替换方式
  • 原文地址:https://www.cnblogs.com/caicairui/p/7748380.html
Copyright © 2011-2022 走看看