• Python读写文件学习笔记


    一. 基础

    1.创建文件夹

    import os
    
    os.makedirs('I:\pythonWorkPace')  # 创建文件夹

    2. 获取文件夹里面文件列表

    import os
    
    # os.makedirs('I:\pythonWorkPace')  # 创建文件夹
    
    path = 'I:\pythonWorkPace'
    filelist = os.listdir(path)  # 获取文件夹里面文件列表
    print(filelist)

    3. 统计文件夹下面文件的所有文件大小

    import os
    
    path = 'I:\pythonWorkPace'
    filelist = os.listdir(path)  # 获取文件夹里面文件列表# 统计文件夹下面文件的所有文件大小
    totalSize = 0;
    for fileName in filelist:
        fileSize = os.path.getsize(os.path.join(path, fileName))
        print("当前文件的大小:%s" % (fileSize))
        totalSize = totalSize + os.path.getsize(os.path.join(path, fileName))
    print("文件总大小:%s" % (totalSize))

     效果:

    '''
    调用 open() 函数,打开一个 File 文件对象。
    调用 File 的 read() 或 write() 方法进行读取与写入操作。
    调用 File 的 close() 方法,关闭文件。
    要进行完整的读写操作,以上三个步骤缺一不可。
    open() 函数可接受两个参数: open(para1, para2)其中,para2可以为: 为空,则默认采取读模式打开文件。 ‘r’:读模式,即只能读取文件,无法修改。 ‘w’:写模式,即可以向文件中添加文本内容,会覆盖文件原有内容。 ‘a’:添加模式,即在原有内容末尾添加文本内容。 当 open() 函数打开的文件不存在时,写模式和添加模式都会创建一个新的空文件。 每次读取或写入文件后,必须调用 close() 方法将其关闭,才能在此打开该文件。
    '''

    二.读文件

     1.read

    # 文件路径
    filePath = 'I:\pythonWorkPace\py3.txt'
    
    # 打开文件
    # lineFile = open(filePath, 'r')
    lineFile = open(filePath, 'r', encoding='utf-8')  # 这里必须事先知道文件编码格式(防止中文乱码)
    
    # 读成行<list>
    lineContent = lineFile.readlines()
    
    # 原文读
    # readContent = lineFile.read()
    
    # 输出内容
    print(lineContent)
    
    # 输出内容
    # print(readContent)
    
    # 关闭文件
    lineFile.close()

    三.写文件

    import os
    
    '''
    w+每次打开文件,都会清空之前的内容,若文件不存在,则会自动创建
    r+会在之前的基础上追加内容,但是不会创建文件
    所以两个可以一起用,用之前判断一下文件是否存在,如下:
    '''
    # 文件路径
    filePath = 'I:\pythonWorkPace\py3.txt'
    
    # f = open(filePath, 'r+', encoding='utf-8')  # 必须事先知道文件的编码格式,这里文件编码是使用的utf-8
    if os.path.exists(filePath):
        f = open(filePath, 'r+', encoding='utf-8')
    else:
        f = open(filePath, 'w+', encoding='utf-8')
    content = f.read()  # 如果open时使用的encoding和文件本身的encoding不一致的话,那么这里将将会产生错误
    f.write('你想要写入的信息2222')
    f.close()
  • 相关阅读:
    栈的使用
    学习
    JS中常用的工具类
    AOP的相关概念
    Git-用git同步代码
    权限管理3-整合Spring Security
    权限管理2-开发权限管理接口
    权限管理1-需求描述
    使用Canal作为mysql的数据同步工具
    使用存储过程在mysql中批量插入数据
  • 原文地址:https://www.cnblogs.com/coloz/p/10773137.html
Copyright © 2020-2023  润新知