zoukankan      html  css  js  c++  java
  • python之文件操作

    with关键字是让python妥善的打开或关闭文件

    读取整个文件
    # file1.txt
    
    3.1415926
    2.71828
    1.732
    
    with open('file1.txt') as file1:
        file_content=file1.read()
        print(file_content)
        
    结果:
    3.1415926
    2.71828
    1.732
    
    逐行读取文件
    with open('file1.txt') as file1:
        for line in file1:
            print(line.lstrip())
            
    结果:    # 由于每行末尾有一个看不见的换行符,用lstrip消除
    3.1415926
    2.71828
    1.732
    
    

    由于使用了with关键字,open()返回的文件对象只在with代码块中有用,如果要在代码块外面访问文件的内容,可以with代码块内将文件的各行存储在一个列表中

    with open('file1.txt') as file1:
        lines=file1.readlines()
    print(lines)
    
    结果:
    ['3.1415926
    ', '2.71828
    ', '1.732']
    

    open()函数有两个参数,第一个是要操作的文件,第二个是模式:1.'r'读取模式,默认;2.'w'写入模式;3.'a'附加模式;4.'r+'读取与写入模式

    写入空文件
    with open('file1.txt','w') as file1:
        file1.write('aaa')
    
    写入多行
    with open('file1.txt','w') as file1:
        file1.write('aaa
    ')
        file1.write('bbb
    ')
    
    附加到文件
    with open('file1.txt','a') as file1:
        file1.write('aaa
    ')
        file1.write('bbb
    ')
    

    Tips:

    1.如果要写入的文件不存在,函数open()将自动创建它,然而以写入模式打开文件时,如果已存在该文件,python将在返回文件对象前清空该文件
    2.如果要给文件添加附加内容,而不是覆盖原有内容,可以以附加模式打开该文件,如果文件不存在,将会创建一个空文件
    

    存储数据

    json.dump()

    import json
    numbers=[1,2,3,4]
    with open('file1.txt','w') as file1:
        json.dump(numbers,file1)
    
    读取数据

    json.load()

    import json
    numbers=[1,2,3,4]
    with open('file1.txt') as file1:
        a=json.load(file1)
    print(a)
    
    结果:
    [1, 2, 3, 4]
    
  • 相关阅读:
    golang的make
    Go的指针
    vue 修改子组件的数据$refs
    vue中异步函数async和await的用法
    redis锁
    支付宝app支付商户配置
    微信小程序中this.data与this.setData的区别详解
    jQuery动态数字翻滚计数到指定数字的文字特效代码
    中英文判断
    jQuery点击图片弹出大图遮罩层
  • 原文地址:https://www.cnblogs.com/raind/p/9461197.html
Copyright © 2011-2022 走看看