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

    文件操作

    在Python语言中,操作文件需要记住一个函数和三个方法

    函数方法 说明
    open 打开文件,并且返回文件操作对象
    read 将文件内容读取到内存中
    write 将指定内容写入文件
    close 关闭文件
    • open函数负责打开文件,并且返回文件对象
    • read/write/close三个方法都需要调用文件对象来调用

    read方法读取文件

    • open函数的第一个参数是要打开的文件名(文件名区分大小写)
      • 如果文件存在,返回文件操作对象
      • 文件不存在,抛出异常
    • read方法可以一次性读入并且返回文件的所有内容
    • close方法负责关闭文件
    # 打开文件
    file = open("admin.txt")
    
    # 读取文件内容
    text = file.read()
    print(text)
    
    # 关闭文件
    file.close()
    

    打开文件的方式

    • open函数默认只读方式打开文件,并且返回文件对象

    语法如下:

    f = open("文件名", "访问方式")
    
    访问方式 说明
    r 只读的方式打开文件, 默认就是只读
    w 只写的方式打开文件,如果文件存在则进行覆盖。如果不存在,创建新文件
    a 以追加的方式打开文件,如果文件存在,则将内容追加到末尾。如果文件不存在,则创建文件并写入
    r+ 读写的方式打开文件,文件不存在,抛出异常
    w+ 读写的方式打开文件,如果文件存在直接覆盖,文件不存在,创建新文件
    a+ 读写的方式打开文件,如果文件不存在,创建新文件进行写入,文件存在,直接追加
    f = open("file", "w")
    
    f.write("hello, world")
    
    f.close()
    

    按行读取文件内容

    • read方法默认把文件的所有内容一次性读取到内存中
    • 如果文件过大,内存占用会非常严重
    readline方法
    • readline方法可以一次读取一行内容
    • 方法执行之后,会把文件指针移动到下一行,准备再次读取
    file = open("file.txt")
    
    while True:
        text = file.readline()
        # 判断是否有内容
        if not text:
            break
        print(text)
    
    file.close()
    

    文件读写复制案例

    小文件复制
    file_read = open("1.txt")
    file_write = open("1附件.txt")
    
    text = file_read.read()
    file_write.write(text)
    
    file_read.close()
    file_write.close()
    
    大文件复制
    file_read = open("1.txt")
    file_write = open("1附件.txt")
    
    while True:
        text = file_read.readline()
        if not text:
            break
        
        file_write.write(text)
    
    file_read.close()
    file_write.close()
    
    

    文件指针

    • 文件指针是标记从哪个位置开始读取数据
    • 第一次打开文件,通常文件指针会指向文件的开始位置
    • 执行read方法之后,文件指针会移动到内容的末尾

    with open用法

    语法格式

    with open() as f:
        pass
    

    示例代码

    with open("1.txt") as f:
        f.read()
    

    with和上下文管理你想知道吗?下篇文章揭晓

  • 相关阅读:
    Additional Color Tables
    How to make a non-symmetric color pallet around zero
    【cl】cmd相关命令
    【cl】oracle之Sequence
    常用命令之ps
    卸载oracle
    oracle—无法启动
    oracle 导入数据
    proc文件系统漫谈
    GStreamer插件分类
  • 原文地址:https://www.cnblogs.com/liudemeng/p/12272834.html
Copyright © 2011-2022 走看看