python实现文件的读写

python实现文件的读写

  • 路径的书写:

    open("E:\\ai_03\\code\\ai_03_python\\day07\\data.txt")#两个斜杠
    open(r"E:\ai_03\code\ai_03_python\day07\data.txt", "w", encoding="utf8")#建议使用
    
  • 读文件

    • 读文件的格式

      • 要以读文件的模式打开一个文件对象,使用Python内置的open()函数,传入文件名和标示符:

        f = open('c:\\users\\shujia\\desktop\\test.txt', 'r')
        'r'标示符表示读,这样成功地打开了一个文件
        如果文件不存在,open()函数就会抛出一个IOError的错误
        
      • 如果文件成功打开,调用read方法可以把内容读到内存,用一个str对象接收:f.read() 得到’Hello, world!'。

      • 文件使用完毕后调用close()方法可以关闭文件:f.close()。

    • open方法

      • open() 函数常用形式是接收两个参数:文件名(file)和模式(mode)。

        open(file,mode='r',buffering=None,encoding=None,errors=None,newline=None,closefd=True)
        
      • 参数方法

        • file: 必需,文件路径(相对或者绝对路径)。
        • mode: 可选,文件打开模式,默认为r。
        • encoding: 一般使用utf8编码。
        • errors: 报错级别。
        • newline: 区分换行符。
        • buffering: 设置缓冲。
        • closefd: 传入的file参数类型。
      • 常用的mode

        • ‘r’:读取 open for reading (default)
        • ‘w’:写(关闭后会删去,写非二进制加上:encoding=‘utf8’)open for writing, truncating the file first。
        • ‘x’:创建写(有的话报错,没有就创建)create a new file and open it for writing。
        • ‘a’:追加 open for writing, appending to the end of the file if it exists。
        • ‘b’:二进制 binary mode。
        • ‘+’:更新 可以组合使用 open a disk file for updating (reading and writing)。
        • 不同mode可以相互灵活组合:r、rb、w、wb等。
      • 使用with语句

        • 文件读写时都有可能产生IOError,一旦出错,后面的f.close()就不会调用。Python引入了with语句来自动调用close()方法。

          with open('/path/to/file','r') as f:
              print(f.read())
          
    • read方法

      • read()会一次性读取文件的全部内容(内存可能不够用,可以反复调用read(size)方法,每次最多读取size个字节的内容。)
      • readline()可以每次读取一行内容(不带参数 读取一行,数如果过大 也不会超过这一行)。
      • readlines()一次读取所有内容并按行返回list(参数每到一行 读一行 参数超过一行读完下一行).
  • 写文件

    • 写文件的格式

      • 写文件和读文件是一样的,唯一区别是调用open()函数时,传入标识符’w’或者’wb’表示写文本文件或写二进制文件:

        • 先打开文件:f = open(‘c:\users\shujia\desktop\test.txt/test.txt’, ‘w’)
        • 通过write方法写入:f.write(‘Hello, world!’),可以反复调用write()
        • 最后关闭文件:f.close()
      • 写文件同样可以使用with语句,保证把没有写入的数据全部写入磁盘。can

        with open('/path/to/file','w') as f:
            f.write('hello world')
        
  • 参考代码

if __name__ == '__main__':
    # 相对位置 和 绝对位置
    # 绝对位置 从盘符开始输入路径
    # open("E:\\ai_03\\code\\ai_03_python\\day07\\data.txt")
    fp = open(r"E:\ai_03\code\ai_03_python\day07\data.txt", "w", encoding="utf8")
    # ========= ===============================================================
    # Character Meaning
    # --------- ---------------------------------------------------------------
    # 'r'       open for reading (default)
    # 'w'       open for writing, truncating the file first
    # 'x'       create a new file and open it for writing
    # 'a'       open for writing, appending to the end of the file if it exists
    # 'b'       binary mode
    # '+'       open a disk file for updating (reading and writing)
    # ========= ===============================================================

    # open("E:/ai_03/code/ai_03_python/day07/data.txt")

    # 写文件
    # write 往里写入字符串
    fp.write("nihao helloworld\n")
    print(fp.writable())
    fp.writelines("nihao")
    # writelines可以写入字符串列表 把列表合并成大字符串
    fp.writelines(["asdad", "dasdadada", "\n", "eeeeee"])
    fp.close()

    # 读文件
    # 相对位置 存在i相对的概念 ./ 表示同级文件夹下   ../ 表示上级目录下
    f2 = open(r"../day04/homework", "r", encoding="utf8")
    # read 不传参 取所有数据
    # read 传参 取几个字符
    # 读取时候 如果同一次读取 就继续往后读
    print(f2.read(1))
    print(f2.read(1))
    print(f2.readline())
    print(f2.readline())
    # readline 不带参数 读取一行
    # 带参数 读几个字符
    print(f2.readline(6))
    # 参数如果过大 也不会超过这一行
    print(f2.readline(100))
    # readlines 返回的参数数列表
    # 参数没到一行 读一行  参数超过一行读完下一行
    print(f2.readlines(34))
    # 读取所有的行 存入列表中
    print(f2.readlines())
    f2.close()
    pass
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值