zoukankan      html  css  js  c++  java
  • python 学习之open处理文件

    一,open() 函数 处理文件

    open函数,该函数用于文件处理

    操作文件时,一般需要经历如下步骤:

    • 打开文件
    • 操作文件
    一、打开文件

    文件句柄 = open('文件路径', '模式')
    打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
    复制代码
    1 文件句柄 = open('文件路径','打开模式')

        文件句柄相当于于变量名,文件路径可以写为绝对路径也可以写为相对路径。

    文件句柄可以循环 每次1行
    for line in 文件句柄:
      文件句柄.write("新文件")
    复制代码

    打开文件的模式有:

    • r ,只读模式【默认】
    • w,只写模式【不可读;不存在则创建;存在则清空内容;】
    • x, 只写模式【不可读;不存在则创建,存在则报错】
    • a, 追加模式【不可读; 不存在则创建;存在则只追加内容;】

    "+" 表示可以同时读写某个文件

    • r+, 读写【可读,可写】
    • w+,写读【可读,可写】
    • x+ ,写读【可读,可写】
    • a+, 写读【可读,可写】

     "b"表示以字节的方式操作

    • rb  或 r+b 
    • wb 或 w+b
    • xb 或 w+b
    • ab 或 a+b

     注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型

      

    复制代码
    文件 hello.txt
    Hello Word!
    123
    abc
    456
    abc
    789
    abc
    刘建佐
    
    代码 :
    f = open("hello.txt",'rb') # 用到b模式的时候 就不能跟 编码了。
    data = f.read()
    f.close()
    print(data)
    
    输出
    C:Python35python3.exe E:/py_test/s5/open.py
    b'Hello Word!
    123
    abc
    456
    abc
    789
    abc
    xe5x88x98xe5xbbxbaxe4xbdx90'
    复制代码

    python open函数 r 和rb区别

    下面着重讲解下用"+" 同时读写某个文件的操作

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    # r+形式 写的时候在末尾追加,指针移到到最后
    # 大家一定要清楚的明白读写的时候指针指向的位置,下面的这个例子一定要懂
    # f.tell()   读取指针的位置
    # f.seek(0)  设置指针的位置
    with open('1.txt','r+',encoding='utf-8') as f:
        print(f.tell())            #打印下 文件开始时候指针指向哪里 这里指向 0
        print(f.read())            #读出文件内容'字符串',
        print(f.tell())            #文件指针指到 9,一个汉子三个字符串,指针是以字符为单位
        f.write('科比')            #写入内容'科比',需要特别注意此时文件指到文件末尾去了
        print(f.read())            #指针到末尾去了,所以读取的内容为空
        print(f.tell())            #指针指到15
        f.seek(0)                  #将指针内容指到 0 位置
        print(f.read())            #因为文件指针指到开头去了,所以可以读到内容 字符串科比
      
    # w+形式 存在的话先清空 一写的时候指针到最后
    with open('1.txt','w+') as f:
        f.write('Kg')               #1.txt存在,所以将内面的内容清空,然后再写入 'kg'
        print(f.tell())             #此时指针指向2
        print(f.read())             #读不到内容,因为指针指向末尾了
        f.seek(0)
        print(f.read())             #读到内容,因为指针上一步已经恢复到起始位置
          
    # a+打开的时候指针已经移到最后,写的时候不管怎样都往文件末尾追加,这里就不再演示了,读者可以自己试一下
    # x+文件存在的话则报错,也不演示了

      

    Python文件读取方式

    模式 说明
    read([size]) 读取文件全部内容,如果设置了size,那么就读取size字节
    readline([size]) 一行一行的读取
    readlines() 读取到的每一行内容作为列表中的一个元素

    二、操作

      1 class file(object)
      2     def close(self): # real signature unknown; restored from __doc__
      3         关闭文件
      4         """
      5         close() -> None or (perhaps) an integer.  Close the file.
      6          
      7         Sets data attribute .closed to True.  A closed file cannot be used for
      8         further I/O operations.  close() may be called more than once without
      9         error.  Some kinds of file objects (for example, opened by popen())
     10         may return an exit status upon closing.
     11         """
     12  
     13     def fileno(self): # real signature unknown; restored from __doc__
     14         文件描述符  
     15          """
     16         fileno() -> integer "file descriptor".
     17          
     18         This is needed for lower-level file interfaces, such os.read().
     19         """
     20         return 0    
     21  
     22     def flush(self): # real signature unknown; restored from __doc__
     23         刷新文件内部缓冲区
     24         """ flush() -> None.  Flush the internal I/O buffer. """
     25         pass
     26  
     27  
     28     def isatty(self): # real signature unknown; restored from __doc__
     29         判断文件是否是同意tty设备
     30         """ isatty() -> true or false.  True if the file is connected to a tty device. """
     31         return False
     32  
     33  
     34     def next(self): # real signature unknown; restored from __doc__
     35         获取下一行数据,不存在,则报错
     36         """ x.next() -> the next value, or raise StopIteration """
     37         pass
     38  
     39     def read(self, size=None): # real signature unknown; restored from __doc__
     40         读取指定字节数据
     41         """
     42         read([size]) -> read at most size bytes, returned as a string.
     43          
     44         If the size argument is negative or omitted, read until EOF is reached.
     45         Notice that when in non-blocking mode, less data than what was requested
     46         may be returned, even if no size parameter was given.
     47         """
     48         pass
     49  
     50     def readinto(self): # real signature unknown; restored from __doc__
     51         读取到缓冲区,不要用,将被遗弃
     52         """ readinto() -> Undocumented.  Don't use this; it may go away. """
     53         pass
     54  
     55     def readline(self, size=None): # real signature unknown; restored from __doc__
     56         仅读取一行数据
     57         """
     58         readline([size]) -> next line from the file, as a string.
     59          
     60         Retain newline.  A non-negative size argument limits the maximum
     61         number of bytes to return (an incomplete line may be returned then).
     62         Return an empty string at EOF.
     63         """
     64         pass
     65  
     66     def readlines(self, size=None): # real signature unknown; restored from __doc__
     67         读取所有数据,并根据换行保存值列表
     68         """
     69         readlines([size]) -> list of strings, each a line from the file.
     70          
     71         Call readline() repeatedly and return a list of the lines so read.
     72         The optional size argument, if given, is an approximate bound on the
     73         total number of bytes in the lines returned.
     74         """
     75         return []
     76  
     77     def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
     78         指定文件中指针位置
     79         """
     80         seek(offset[, whence]) -> None.  Move to new file position.
     81          
     82         Argument offset is a byte count.  Optional argument whence defaults to
     83 (offset from start of file, offset should be >= 0); other values are 1
     84         (move relative to current position, positive or negative), and 2 (move
     85         relative to end of file, usually negative, although many platforms allow
     86         seeking beyond the end of a file).  If the file is opened in text mode,
     87         only offsets returned by tell() are legal.  Use of other offsets causes
     88         undefined behavior.
     89         Note that not all file objects are seekable.
     90         """
     91         pass
     92  
     93     def tell(self): # real signature unknown; restored from __doc__
     94         获取当前指针位置
     95         """ tell() -> current file position, an integer (may be a long integer). """
     96         pass
     97  
     98     def truncate(self, size=None): # real signature unknown; restored from __doc__
     99         截断数据,仅保留指定之前数据
    100         """
    101         truncate([size]) -> None.  Truncate the file to at most size bytes.
    102          
    103         Size defaults to the current file position, as returned by tell().
    104         """
    105         pass
    106  
    107     def write(self, p_str): # real signature unknown; restored from __doc__
    108         写内容
    109         """
    110         write(str) -> None.  Write string str to file.
    111          
    112         Note that due to buffering, flush() or close() may be needed before
    113         the file on disk reflects the data written.
    114         """
    115         pass
    116  
    117     def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
    118         将一个字符串列表写入文件
    119         """
    120         writelines(sequence_of_strings) -> None.  Write the strings to the file.
    121          
    122         Note that newlines are not added.  The sequence can be any iterable object
    123         producing strings. This is equivalent to calling write() for each string.
    124         """
    125         pass
    126  
    127     def xreadlines(self): # real signature unknown; restored from __doc__
    128         可用于逐行读取文件,非全部
    129         """
    130         xreadlines() -> returns self.
    131          
    132         For backward compatibility. File objects now include the performance
    133         optimizations previously implemented in the xreadlines module.
    134         """
    135         pass
    136 
    137 2.x
    138 
    139 2.x Code
    View Code
    class TextIOWrapper(_TextIOBase):
        """
        Character and line based layer over a BufferedIOBase object, buffer.
        
        encoding gives the name of the encoding that the stream will be
        decoded or encoded with. It defaults to locale.getpreferredencoding(False).
        
        errors determines the strictness of encoding and decoding (see
        help(codecs.Codec) or the documentation for codecs.register) and
        defaults to "strict".
        
        newline controls how line endings are handled. It can be None, '',
        '
    ', '
    ', and '
    '.  It works as follows:
        
        * On input, if newline is None, universal newlines mode is
          enabled. Lines in the input can end in '
    ', '
    ', or '
    ', and
          these are translated into '
    ' before being returned to the
          caller. If it is '', universal newline mode is enabled, but line
          endings are returned to the caller untranslated. If it has any of
          the other legal values, input lines are only terminated by the given
          string, and the line ending is returned to the caller untranslated.
        
        * On output, if newline is None, any '
    ' characters written are
          translated to the system default line separator, os.linesep. If
          newline is '' or '
    ', no translation takes place. If newline is any
          of the other legal values, any '
    ' characters written are translated
          to the given string.
        
        If line_buffering is True, a call to flush is implied when a call to
        write contains a newline character.
        """
        def close(self, *args, **kwargs): # real signature unknown
            关闭文件
            pass
    
        def fileno(self, *args, **kwargs): # real signature unknown
            文件描述符  
            pass
    
        def flush(self, *args, **kwargs): # real signature unknown
            刷新文件内部缓冲区
            pass
    
        def isatty(self, *args, **kwargs): # real signature unknown
            判断文件是否是同意tty设备
            pass
    
        def read(self, *args, **kwargs): # real signature unknown
            读取指定字节数据
            pass
    
        def readable(self, *args, **kwargs): # real signature unknown
            是否可读
            pass
    
        def readline(self, *args, **kwargs): # real signature unknown
            仅读取一行数据
            pass
    
        def seek(self, *args, **kwargs): # real signature unknown
            指定文件中指针位置
            pass
    
        def seekable(self, *args, **kwargs): # real signature unknown
            指针是否可操作
            pass
    
        def tell(self, *args, **kwargs): # real signature unknown
            获取指针位置
            pass
    
        def truncate(self, *args, **kwargs): # real signature unknown
            截断数据,仅保留指定之前数据
            pass
    
        def writable(self, *args, **kwargs): # real signature unknown
            是否可写
            pass
    
        def write(self, *args, **kwargs): # real signature unknown
            写内容
            pass
    
        def __getstate__(self, *args, **kwargs): # real signature unknown
            pass
    
        def __init__(self, *args, **kwargs): # real signature unknown
            pass
    
        @staticmethod # known case of __new__
        def __new__(*args, **kwargs): # real signature unknown
            """ Create and return a new object.  See help(type) for accurate signature. """
            pass
    
        def __next__(self, *args, **kwargs): # real signature unknown
            """ Implement next(self). """
            pass
    
        def __repr__(self, *args, **kwargs): # real signature unknown
            """ Return repr(self). """
            pass
    
        buffer = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    
        closed = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    
        encoding = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    
        errors = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    
        line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    
        name = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    
        newlines = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    
        _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    
        _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    
    3.x
    
    3.x
    View Code

     操作示例:

        测试的文件名是 "hello.txt" ,文件内容为:

    复制代码
    Hello Word!
    123
    abc
    456
    abc
    789
    abc
    复制代码

    read 方法
      代码:

    复制代码
    # 以只读的方式打开文件hello.txt
    f = open("hello.txt","r")
    # 读取文件内容赋值给变量c
    c = f.read()
    # 关闭文件
    f.close()
    # 输出c的值
    print(c)

    输出结果

    C:Python35python3.exe E:/py_test/s5/open.py
    Hello Word!
    123
    abc
    456
    abc
    789
    abc

    复制代码

    readline
      代码:

    复制代码
    # 以只读模式打开文件hello.txt
    f = open("hello.txt","r")
    # 读取第一行  strip 去除空行
    c1 = f.readline().strip()
    # 读取第二行 
    c2 = f.readline().strip()
    # 读取第三行
    c3 = f.readline().strip()
    # 关闭文件
    f.close()
    # 输出读取文件第一行内容
    print(c1)
    # 输出读取文件第二行内容
    print(c2)
    # 输出读取文件第三行内容
    print(c3)

    C:Python35python.exe F:/Python_code/sublime/Day06/file.py
    Hello Word!
    123
    abc
    复制代码

    readlines 获取到的是列表,每行是列表的元素

      用法

    复制代码
    # 以只读的方式打开文件hello.txt
    f = open("hello.txt","r")
    # 将文件所有内容赋值给c
    c = f.readlines()
    # 查看数据类型
    print(type(c))
    # 关闭文件
    f.close()
    # 遍历输出文件内容 # n.strip()去除空行
    for n in c:
        print(n.strip())
    复制代码

    Python文件写入方式

    方法 说明
    write(str)  将字符串写入文件 ,原文件内容存在则清空,不存在新建
    writelines(sequence or strings) 写多行到文件,参数可以是一个可迭代的对象,列表、元组等

    write
      代码:

    复制代码
    # 以只读的模式打开文件write.txt,没有则创建,有则覆盖内容
    file = open("write.txt","w")
    # 在文件内容中写入字符串test write
    file.write("test write")
    # 关闭文件
    file.close()
    复制代码

    writeline
      代码:

    复制代码
    # 以只读模式打开一个不存在的文件wr_lines.txt
    f = open("wr_lines.txt","w",encoding="utf-8")
    # 写入一个列表
    f.writelines(["11","22","33"])
    # 关闭文件
    f.close()
    复制代码

    wr_lines.txt 文件内容:

    112233

    Python文件操作所提供的方法

    close(self):
      关闭已经打开的文件

    f.close()

    fileno(self):
      文件描述符

    f = open("hello.txt",'rb')
    data = f.fileno()
    f.close()
    print(data)

      输出结果

      

      C:Python35python3.exe E:/py_test/s5/open.py
      3

    flush(self):
      刷新缓冲区的内容到硬盘中

    f.flush() #在r+ 或者 rb+模式下还没有 f.close() 或者之后,flush方法 就会将内存的数据写入硬盘。 否则在其他地方调用这个文件的新内容会找不到

    isatty(self):
      判断文件是否是tty设备,如果是tty设备则返回 True ,否则返回 False

    f = open("hello.txt","r")
    ret = f.isatty()
    f.close()
    print(ret)

    返回结果:

    C:Python35python.exe F:/Python_code/sublime/Day06/file.py
    False

    readable(self):
      是否可读,如果可读返回 True ,否则返回 False

    f = open("hello.txt","r")
    ret = f.readable()
    f.close()
    print(ret)

    返回结果:

    C:Python35python.exe F:/Python_code/sublime/Day06/file.py
    True

    readline(self, limit=­1):
      每次仅读取一行数据

    f = open("hello.txt","r")
    print(f.readline())
    print(f.readline())
    f.close()

    返回结果:

    C:Python35python.exe F:/Python_code/sublime/Day06/file.py
    Hello Word!
    123

    readlines(self, hint=­1):
      把每一行内容当作列表中的一个元素

    f = open("hello.txt","r")
    print(f.readlines())
    f.close()

    返回结果:

    C:Python35python.exe F:/Python_code/sublime/Day06/file.py
    ['Hello Word!
    ', '123
    ', 'abc
    ', '456
    ', 'abc
    ', '789
    ', 'ab
    c']

    tell(self):
      获取指针位置

    f = open("hello.txt","r")
    print(f.tell())
    f.close()

    返回结果:

    C:Python35python.exe F:/Python_code/sublime/Day06/file.py
    0

    seek(self, offset, whence=io.SEEK_SET):
      指定文件中指针位置

    f = open("hello.txt","r")
    print(f.tell())
    f.seek(3)
    print(f.tell())
    f.close()

    执行结果

    C:Python35python.exe F:/Python_code/sublime/Day06/file.py
    0 3

    seekable(self):
      指针是否可操作

    f = open("hello.txt","r")
    print(f.seekable())
    f.close()

    执行结果

    C:Python35python.exe F:/Python_code/sublime/Day06/file.py
    True

    writable(self):
      是否可写

    f = open("hello.txt","r")
    print(f.writable())
    f.close()

    执行结果

    C:Python35python.exe F:/Python_code/sublime/Day06/file.py
    False

    writelines(self, lines):
      写入文件的字符串序列,序列可以是任何迭代的对象字符串生产,通常是一个 字符串列表 。

    f = open("wr_lines.txt","w")
    f.writelines(["11","22","33"])
    f.close()

    执行结果

    112233

    read(self, n=None):
      读取指定字节数据,后面不加参数默认读取全部

    f = open("wr_lines.txt","r")
    print(f.read(3))
    f.seek(0)
    print(f.read())
    f.close()

    执行结果

    C:Python35python.exe F:/Python_code/sublime/Day06/file.py
    112
    112233

    write(self, s):
      往文件里面写内容

    f = open("wr_lines.txt","w")
    f.write("abcabcabc")
    f.close()

    文件内容

    abcabcabc
  • 相关阅读:
    java之认识基本数据类型及其封装类装箱和拆箱总结
    java之集合类特性对比分析列表
    <转>泛型的内部原理:类型擦除以及类型擦除带来的问题
    java之集合类框架的简要知识点:泛型的类型擦除
    java之方法覆盖的坑
    java入门概念个人理解之访问修饰符
    blog开篇
    卓越管理的实践技巧(4)如何才能给予有效的反馈 Guide to Giving Effective Feedback
    权限管理系统之组织管理
    卓越管理的实践技巧(3)推动团队管理的要点 Facilitation Essentials for Managers
  • 原文地址:https://www.cnblogs.com/superfangchao/p/8520685.html
Copyright © 2011-2022 走看看