zoukankan      html  css  js  c++  java
  • open()函数文件操作

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

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

        (1)打开文件

      (2)操作文件

      一、打开文件

        文件句柄 = open("文件路径","模式")

        打开文件是,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

        打开文件的模式有:

        (1)r,只读模式【默认】

        (2)w,只写模式不可读;不存在则创建;存在则清空内容】

      (3)x,只写模式不可读;不存在则创建;存在则报错】

      (4)a,追加模式【可读;不存在则创建;存在则只追加内容

      下面是一个简单的例子,判断"w"模式下的文件是否可读,因为以前一致没有注意,不知道"w"模式下文件不可读。实例如下:

        with open("test.log","w") as f:
        f.write("123 ")
        f.write("I love python ")
        f.write("I must to work hard ")
        f.write("I must to write string in the file ")
        #判断文件是否可读readable()
        ret = f.readable()
      
      print(ret)

      运行如下:

      False

        首先,我们用"w"只写模式打开文件,并向文件中添加内容,然后使用readable()判断文件是否可读,结果返回False,说明文件是不可读的。

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

      (1)r+,读写【可读,可写】

      (2)w+,写读【可读,可写】

      (3) x+,写读【可读,可写】

      (4)a+,写读【可读,可写】

      "U"表示在读取时,可以将 自动转化成(与r或r+模式同时使用)

        (1)U

      (2)r+U

      "b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

        (1)rb或r+b

      (2)wbw+b

      (3)xbx+b

      (4)aba+b

      二、操作文件

       (1)def close(self):

        # real signature unknown; restored from __doc__

      关闭文件

       """

      (2def fileno(self):

        # real signature unknown; restored from __doc__

            文件描述符  
             """ 
      (3)def flush(self):
         # real signature unknown; restored from __doc__
        刷新文件内部缓冲区
         """
        flush() -> None. Flush the internal I/O buffer. """ pass
      (4)def isatty(self):
        # real signature unknown; restored from __doc__
        判断文件是否是同意tty设备
        """
        isatty() -> true or false. True if the file is connected to a tty device.
         """
        return False
      (5)def next(self)
        # real signature unknown; restored from __doc__
        取下一行数据,不存在,则报错
         """ x.next() -> the next value, or raise StopIteration """
         pass
      (6)def read(self, size=None):
         # real signature unknown; restored from __doc__
        读取指定字节数据
        """
      
    read()是读取文件,可以指定读取文件中字符串多少个字节,read(self,size=None)默认是全部读取,在Python3中是按照字符来读取的。读取文件。
    with open("test.log","r") as f:
      ret = f.read(3)

      print(ret)
      运行如下:

      我是你
      上述代码我们以只读模式打开文件,并且读取文件中3个字符长度。
      (7)
    def readline(self, size=None):
         # real signature unknown; restored from __doc__
        仅读取一行数据
        """

       readlin(self,size=None)仅读取一行,经常和readlines()混淆,原来readline()是仅读取一行,readlines()按照换行符读取到一个列表中。示例如
    下:

    with open("test.log","r") as f:
    ret = f.readline()
    res = f.readline(2)

      print(ret)
      print(res)
      运行结果如下:
      在Python中只能写入字符串
      我喜
      上面代码可以看出,readline()读取了文件的第一行,并且readline(self,size)可以指定读取第一行的字符个数;并且如果第一行读取完成之后,是
    不能同时进行读取的,就会读取第二行的内容。
    (8)readable(self,*args,**kwargs)
       readable(self,*args,**kwargs)是判断文件是否可读,如果可以读取就返回布尔值True;否则返回波尔值False.
      (9)
    def seek(self, offset, whence=None)
        # real signature unknown; restored from __doc__ 指定文件中指针位置 """  
      seek(self,offset,whence=None)指定文件指针的位置,指定从哪里进行读取,实例如下:

      with open("test.log","r") as f:
      #print(f.tell())
       #插入指针的位置
       f.seek(3)
       #read()是按照字符来读取的
      ret = f.read(2)
       #tell是按照字节来读取的,汉字有3个字节,两个汉字有6个字节
       print(f.tell())
      #tell用来查看当前指针位置
       #seek指定当前指针位置
      print(ret)
      seek(self,offset,whence=None)是指定文件从那里开始读取,以字节的方式。
      tell(self)用来查看当前文件的指针,就是读取之后下一次从哪里开始读取。
    10.
    def tell(self):
         # real signature unknown; restored from __doc__ 获取当前指针位置 """ tell() -> current file position, an integer (may be a long integer). """ pass
      tell(self)是获取当前文件的指针位置。
      11.
    def truncate(self, size=None):
      #
    real signature unknown; restored from __doc__ 截断数据,仅保留指定之前数据 """ truncate([size]) -> None. Truncate the file to at most size bytes. Size defaults to the current file position, as returned by tell(). """ pass
    truncate(self,size=None)获取截断数据之前的数据。使用seek()截断数据,read()只读取截断文件之后的数据,之前的数据不管;而truncate()是读取
    截断之前的数据。示例如下:
      

      with open("test.log","r+") as f:
      #print(f.tell())
      #插入指针的位置
      f.seek(6)
       #读取截断之后的文件内容
       #ret = f.read()
       #读取截断文件之前的文件内容
       res = f.truncate()
      #print(ret)
      print(res)
      truncate(self,size=None)是截取文件指针之前的内容,并把指针后面的文件删除,只保留指针之前的文件信息。
    12.
    def seekable(self, *args, **kwargs):
         # real signature unknown 指针是否可操作 pass

    13. def writable(self, *args, **kwargs):
        #
    real signature unknown 是否可写 pass  

       14.def write(self, *args, **kwargs):

         # real signature unknown

            写内容
            pass

       15.def writelines(self, sequence_of_strings):

          # real signature unknown; restored from __doc__

             将一个字符串列表写入文件,示例如下:
      with open("test.log","w") as f:
      li = ["I love you. ", "I need to work hard to do someing. ", "In the Python,you can't to write int in the file"]
      f.writelines(li)
      上述代码中,我们把一个字符串列表写入了文件中。readlines(self,sequence_of_strings)以字符串列表的形式向文件中写入内容。
    16.
    def readlines(self, size=None):
        # real signature unknown; restored from __doc__ 读取所有数据,并根据换行保存值列表 """
      readlines(self,size=None)读取文件所有数据,并且以换行符的形式存储在一个列表中,与writelines()类似,实例如下:

      with open("test.log","r") as f:
      ret = f.readlines()

      print(ret)
      运行结果如下:
    ['I love you. ', 'I need to work hard to do someing. ', "In the Python,you can't to write int in the file"]
    with open("test.log","r") as f:
    ret = f.readline()
    res = f.readline(2)

    print(ret)
    print(res)
  • 相关阅读:
    LeetCode(287)Find the Duplicate Number
    LeetCode(290) Word Pattern
    LeetCode(205)Isomorphic Strings
    LeetCode(201) Bitwise AND of Numbers Range
    LeetCode(200) Number of Islands
    LeetCode(220) Contains Duplicate III
    LeetCode(219) Contains Duplicate II
    命令行执行Qt程序
    LeetCode(228) Summary Ranges
    redis 的安装和使用记录
  • 原文地址:https://www.cnblogs.com/gengcx/p/6788758.html
Copyright © 2011-2022 走看看