zoukankan      html  css  js  c++  java
  • python基础之文件操作

    文件操作有很多种

      我们在这里可以大体分一下,文件的操作其实可以分为对文件整体的操作(创建文件,删除文件,重命名文件,获取文件属性)以及对文件内容的操作(修改文件内容

      先来看对文件整体的操作:

    我们按照增删查改的顺序进行讲述

    1  增

      所谓增,即新建。

    新建一个文件

    f=open('lalal','w+')    #如果该文件(lalal)不存在则创建,若存在则打开。open函数会返回一个文件描述符

    新建一个目录:

    >>> os.listdir()
    ['log', 'test1']
    >>> os.mkdir('bin')
    >>> os.listdir()
    ['log', 'bin', 'test1']

    2  删

      所谓删,也就是删除。

    删除文件:

    >>> import os
    >>> os.listdir()
    ['log', 'test', 'bin', 'test1']
    >>> os.remove('test')     #仅仅只能删除文件,如果删除目录的话会报错。
    >>> os.listdir()
    ['log', 'bin', 'test1']

    删除目录:

    >>> os.rmdir('bin')
    >>> os.listdir()
    ['log', 'test1']

    3  查

      查看文件的各种属性,如:目录下包含的文件,创建时间  修改时间  访问时间  文件权限  文件大小……

    查看目录下包含的文件以及目录:

    >>> os.listdir()
    ['log', 'bin', 'test1']

    获取文件/目录信息:

    >>> os.stat('test1')
    os.stat_result(st_mode=33188, st_ino=137156, st_dev=2050, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1463225144, st_mtime=1463225144, st_ctime=1463225144)

    4  改

    修改文件/目录的权限:

    >>> os.stat('test1')
    os.stat_result(st_mode=33188, st_ino=137156, st_dev=2050, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1463225144, st_mtime=1463225144, st_ctime=1463225144)
    >>> os.chmod('test1',3)           
    >>> os.stat('test1')
    os.stat_result(st_mode=32771, st_ino=137156, st_dev=2050, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1463225144, st_mtime=1463225144, st_ctime=1463225965)
    
    
    
    [root@slyoyo python_test]# lsa
    total 16
    drwxr-xr-x. 4 root root 4096 May 14 04:31 .
    dr-xr-x---. 5 root root 4096 May 14 04:25 ..
    drwxr-xr-x. 2 root root 4096 May 14 04:31 bin
    drwxr-xr-x. 2 root root 4096 May 14 04:25 log
    -rw-r--r--. 1 root root    0 May 14 04:25 test1
    [root@slyoyo python_test]# lsa
    total 16
    drwxr-xr-x. 4 root root 4096 May 14 04:31 .
    dr-xr-x---. 5 root root 4096 May 14 04:25 ..
    drwxr-xr-x. 2 root root 4096 May 14 04:31 bin
    drwxr-xr-x. 2 root root 4096 May 14 04:25 log
    --------wx. 1 root root    0 May 14 04:25 test1
    View Code

    修改文件内容(读写文件)

      读写文件前,我们先必须了解一下,在磁盘上读写文件的功能都是由操作系统提供的,现代操作系统不允许普通的程序直接操作磁盘,所以,读写文件就是请求操作 系统打开一个文件对象(通常称为文件描述符),然后,通过操作系统提供的接口从这个文件对象中读取数据(读文件),或者把数据写入这个文件对象(写文件)。

      我们知道文件对象就是一个类,我们先来看一看python是如何实现这个类的。

    class _IOBase(object):
        """
        The abstract base class for all I/O classes, acting on streams of
        bytes. There is no public constructor.
        是所有I/O类的基类,工作于字节流
    
        This class provides dummy implementations for many methods that
        derived classes can override selectively; the default implementations
        represent a file that cannot be read, written or seeked.
    
        Even though IOBase does not declare read, readinto, or write because
        their signatures will vary, implementations and clients should
        consider those methods part of the interface. Also, implementations
        may raise UnsupportedOperation when operations they do not support are
        called.
    
        The basic type used for binary data read from or written to a file is
        bytes. bytearrays are accepted too, and in some cases (such as
        readinto) needed. Text I/O classes work with str data.
    
        Note that calling any method (except additional calls to close(),
        which are ignored) on a closed stream should raise a ValueError.
    
        IOBase (and its subclasses) support the iterator protocol, meaning
        that an IOBase object can be iterated over yielding the lines in a
        stream.
    
        IOBase also supports the :keyword:`with` statement. In this example,
        fp is closed after the suite of the with statement is complete:
    
        with open('spam.txt', 'r') as fp:
            fp.write('Spam and eggs!')
        """
        def close(self, *args, **kwargs): # real signature unknown
            """
            Flush and close the IO object. flush(刷写到磁盘)并关闭I/O对象
    
            This method has no effect if the file is already closed.
            """
            pass
    
        def fileno(self, *args, **kwargs): # real signature unknown
            """
            Returns underlying file descriptor if one exists. 返回一个文件描述符
    
            An IOError is raised if the IO object does not use a file descriptor.
            """
            pass
    
        def flush(self, *args, **kwargs): # real signature unknown
            """
            Flush write buffers, if applicable. 刷写到磁盘
    
            This is not implemented for read-only and non-blocking streams.
            """
            pass
    
        def isatty(self, *args, **kwargs): # real signature unknown
            """
            Return whether this is an 'interactive' stream.
    
            Return False if it can't be determined.
            """
            pass
    
        def readable(self, *args, **kwargs): # real signature unknown
            """
            Return whether object was opened for reading.
    
            If False, read() will raise UnsupportedOperation.
            """
            pass
    
        def readline(self, *args, **kwargs): # real signature unknown
            """
            Read and return a line from the stream.  读一行
    
            If limit is specified, at most limit bytes will be read.
    
            The line terminator is always b'
    ' for binary files; for text
            files, the newlines argument to open can be used to select the line
            terminator(s) recognized.
            """
            pass
    
        def readlines(self, *args, **kwargs): # real signature unknown
            """
            Return a list of lines from the stream.  将每行读出,形成一个列表并返回
    
            hint can be specified to control the number of lines read: no more
            lines will be read if the total size (in bytes/characters) of all
            lines so far exceeds hint.
            """
            pass
    
        def seek(self, *args, **kwargs): # real signature unknown
            """
            Change stream position.  修改指针位置
    
            Change the stream position to the given byte offset. The offset is
            interpreted relative to the position indicated by whence.  Values
            for whence are:
    
            * 0 -- start of stream (the default); offset should be zero or positive
            * 1 -- current stream position; offset may be negative
            * 2 -- end of stream; offset is usually negative
    
            Return the new absolute position.
            """
            pass
    
        def seekable(self, *args, **kwargs): # real signature unknown
            """
            Return whether object supports random access.
    
            If False, seek(), tell() and truncate() will raise UnsupportedOperation.
            This method may need to do a test seek().
            """
            pass
    
        def tell(self, *args, **kwargs): # real signature unknown
            """ Return current stream position.  返回当前指针位置"""
            pass
    
        def truncate(self, *args, **kwargs): # real signature unknown
            """
            Truncate file to size bytes.  截取当前文件描述符的指针之前的内容
    
            File pointer is left unchanged.  Size defaults to the current IO
            position as reported by tell().  Returns the new size.
            """
            pass
    
        def writable(self, *args, **kwargs): # real signature unknown
            """
            Return whether object was opened for writing.
    
            If False, write() will raise UnsupportedOperation.
            """
            pass
    
        def writelines(self, *args, **kwargs): # real signature unknown
            pass
    
        def _checkClosed(self, *args, **kwargs): # real signature unknown
            pass
    
        def _checkReadable(self, *args, **kwargs): # real signature unknown
            pass
    
        def _checkSeekable(self, *args, **kwargs): # real signature unknown
            pass
    
        def _checkWritable(self, *args, **kwargs): # real signature unknown
            pass
    
        def __del__(self, *args, **kwargs): # real signature unknown
            """  """
            pass
    
        def __enter__(self, *args, **kwargs): # real signature unknown
            pass
    
        def __exit__(self, *args, **kwargs): # real signature unknown
            pass
    
        def __init__(self, *args, **kwargs): # real signature unknown
            pass
    
        def __iter__(self, *args, **kwargs): # real signature unknown
            """ Implement iter(self). """
            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
    
        closed = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    
    
        __dict__ = None # (!) real value is ''
    View Code

    在这个类中,提供了很多方法供我们操作文件描述符或者说文件实例对象。那么问题来了,如何创建或者说获取一个文件描述符?

    使用open获取文件描述符?

    [root@slyoyo python_test]# cat test1 
    hello world
    
    >>> f=open('test1','r+')     #打开文件
    #格式open('file',mode)
    file:文件
    mode:

      w     以写方式打开,
      a     以追加模式打开 (从 EOF 开始, 必要时创建新文件)
      r+     以读写模式打开,不清空文件,指针在文件开头。
      w+     以写读模式打开,会清空文件,指针在文件开头
      a+     以写读模式打开,不清空文件,指针在文件末尾
      rb     以二进制读模式打开
      wb     以二进制写模式打开 
      ab     以二进制追加模式打开 
      rb+    以二进制读写模式打开 
      wb+    以二进制读写模式打开 
      ab+    以二进制读写模式打开 

    如何读文件

    fp.read([size])                    #size为读取的长度,以byte为单位,如果不输入size的话,默认会读取文件的全部内容

    fp.readline([size])              #读一行,如果定义了size,有可能返回的只是一行的一部分。当返回空字符串时,表示文件末尾。

    fp.readlines([size])           #把文件每一行作为一个list的一个成员,并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参               #数,size是表示读取内容的总长,也就是说可能只读到文件的一部分。

    [root@slyoyo python_test]# cat test1 
    hello world
    my name is liming
    i live in shijiazhuang
    a city not far from beijing
    
    >>> f=open('test1','r')
    >>> f.read()
    'hello world
    my name is liming
    i live in shijiazhuang
    a city not far from beijing
    '
    
    >>> f=open('test1','r')
    >>> f.readline()
    'hello world
    '
    
    >>> f=open('test1','r')
    >>> f.readlines()
    ['hello world
    ', 'my name is liming
    ', 'i live in shijiazhuang
    ', 'a city not far from beijing
    ']


    如何写文件?

    fp.write(str)                      #把str写到文件中,write()并不会在str后加上一个换行符

    fp.writelines(seq)            #把seq的内容全部写到文件中(多行一次性写入)。这个函数也只是忠实地写入,不会在每行后面加上任何东西。

    >>> f=open('test1','w+')
    >>> f.read()
    ''      #当以写入的方式打开一个文件时,文件的原内容就不存在了
    
    >>> sentence=["Everbody will make mistakes
    ","that's why they put erasers on the end of pencils.
    "]
    >>> f.writelines(sentence)
    >>> f.readlines()
    []        #即使写入了内容,新内容仍无法见。
    >>> f.close()
    >>> f=open('test1','r')
    >>> f.read()
    "Everbody will make mistakes
    that's why they put erasers on the end of pencils.
    "

    其他方法

    fileobj.seek(offset,whence=0)   从文件中移动off个操作标记(文件指针),正往结束方向移动,负往开始方向移动。如果设定了whence参数,就以whence设定的起始位为 准,0代表从头开始,1代表当前位置,2代表文件最末尾位置。

    fileobj.tell()  返回指针的位置

    示例

    fileobj.flush()  打开文件后,实际上就是在内存中对文件进行修改,使用flush则会将内存中的内容保存到磁盘上。close也有这样的功能。

  • 相关阅读:
    VMware Workstation Pro下载密钥
    hypervisor
    Xmanager6 下载地址
    linux常用命令
    linux常用
    查看机器端口信息
    windows下快捷键
    SpringMVC学习笔记整理
    2017面试题收集
    oracle 常用知识点整理
  • 原文地址:https://www.cnblogs.com/MnCu8261/p/5493184.html
Copyright © 2011-2022 走看看