zoukankan      html  css  js  c++  java
  • 【Python】学习笔记十一:文件I/O

    文件I/O是Python中最重要的技术之一,在Python中对文件进行I/O操作是非常简单的。

    1.打开文件

    语法:

    open(name[, mode[, buffering]])

    1.1文件模式

    1 'r'                 读模式
    2 'w'                 写模式
    3 'a'                 追加模式
    4 'b'                 二进制模式(可添加到其他模式使用)
    5 '+'                 读/写模式(可添加其他模式使用)

    1.2缓冲区

    open 函数的第三个参数( buffering ),表示文件的缓冲,当缓冲区大于0时(等于0时无缓冲,所有的读写操作都直接针对硬盘),Python会将文件内容存放到缓冲区(内存中),从而是程序运行的的更快,这时,只有使用 flush 或者 close 时才会将缓冲区中的数据更新到硬盘中。

    2.文件的读写

    2.1写入文件

    #!/usr/bin/python
    #-*- coding:UTF-8 -*-
    #打开文件
    f = open(r'D:pythonFilePra_1.txt','w')
    
    try :
         #写入文件
         f.write('My name is OLIVER')
    
    finally:
         #关闭文件
          f.close()

    2.2读取文件

    #!/usr/bin/python
    #-*- coding:UTF-8 -*-
    f = open(r'D:pythonFilePra_1.txt','r')
    print(f.read())
    f.close()

    3.文件特殊读取

    3.1遍历每个字符,一次读取

    方法一:

    #!/usr/bin/python
    #-*- coding:UTF-8 -*-
    f = open(r'D:pythonFilePra_1.txt','r')
    
    char = f.read(1)
    while char:
        print(char)
        char = f.read(1)
    f.close()

    方法二:

    #!/usr/bin/python
    #-*- coding:UTF-8 -*-
    f = open(r'D:pythonFilePra_1.txt','r')
    while True:
        line = f.read(1)
        if not line:break
        print(line)
    f.close()

    3.2遍历每一行读取

    Pra_2.txt文件内容:

    #!/usr/bin/python
    #-*- coding:UTF-8 -*-
    f = open(r'D:pythonFilePra_2.txt','r')
    
    while True:
        line = f.readline()
        if not line:break
        print(line)
    f.close()

     读取结果:

  • 相关阅读:
    面向消息的持久通信与面向流的通信
    通信协议
    [1]序章,基本
    深拷贝和浅拷贝
    堆/栈 内存管理相关
    C++的四种cast(显示类型转换)
    智能指针相关
    C++对象模型:单继承,多继承,虚继承
    HTTP/TCP
    [读书笔记] 为什么绝不在构造/析构函数中调用virtual函数
  • 原文地址:https://www.cnblogs.com/OliverQin/p/6074677.html
Copyright © 2011-2022 走看看