• Python 文件操作


    一 介绍

    计算机系统分为:计算机硬件,操作系统,应用程序三部分。

    我们用python或其他语言编写的应用程序若想要把数据永久保存下来,必须要保存于硬盘中,这就涉及到应用程序要操作硬件,众所周知,应用程序是无法直接操作硬件的,这就用到了操作系统。操作系统把复杂的硬件操作封装成简单的接口给用户/应用程序使用,其中文件就是操作系统提供给应用程序来操作硬盘虚拟概念,用户或应用程序通过操作文件,可以将自己的数据永久保存下来。

    有了文件的概念,我们无需再去考虑操作硬盘的细节1 #打开文件,得到文件句柄并赋值给一个变量

    f.read() #读取所有内容,光标移动到文件末尾,
    r  只读模式【默认模式,文件必须存在,不存在则抛出异常】

    read(3):

      1. 文件打开方式为文本模式时,代表读取3个字符

      2. 文件打开方式为b模式时,代表读取3个字节

    2 f=open("tset","r",encoding="utf-8")  #句柄(人为定义的)
    3 #操作文件
    4 data=f.read()  #读
    5 print(data)
    6 #关闭文件
    
    tset文件:
    Python isdecimal() 方法检查字符串是否只包含十进制字符。这种方法只存在于unicode对象。
    
    注意:定义一个十进制字符串,只需要在字符串前添加 'u' 前缀即可。
    
    语法
    isdecimal()方法语法:
    
    str.isdecimal()
    参数
    无
    返回值
    如果字符串是否只包含十进制字符返回True,否则返回False。

     

    f.readline() #读取一行内容,光标移动到第二行首部

    with open("tset","r",encoding="utf-8") as f:
        de=f.readline() #文件打印出一行
        print(de)

    输出结果:       

    1 Python isdecimal() 方法检查字符串是否只包含十进制字符。这种方法只存在于unicode对象。
    f.readlines() #读取每一行内容,存放于列表中
    1 with open("tset","r",encoding="utf-8") as f:
    2     de=f.readlines() 
    3     print(de)

    输出结果:      

    1 ['Python isdecimal() 方法检查字符串是否只包含十进制字符。这种方法只存在于unicode对象。
    ', '
    ', "注意]
    w,只写模式【不可读;不存在则创建;存在则清空内容】(覆盖)
    f.write('1111
    222
    ') #针对文本模式的写,需要自己写换行符
    f.write('1111
    222
    '.encode('utf-8')) #针对b模式的写,需要自己写换行符
    f.writelines(['333
    ','444
    ']) #文件模式
    f.writelines([bytes('333
    ',encoding='utf-8'),'444
    '.encode('utf-8')]) #b模式
    1 with open("tsets","w",encoding="utf-8") as f:
    2     de=f.write("hello")
    3     print(de)
    f.flush() #立刻将文件内容从内存刷到硬盘
    with open("tsets","a",encoding="utf-8") as f:
    
        f.write("
    hello")
        f.flush()     #刷新
        import time
        time.sleep(100)

    a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

    可读可写:

    r+   (可读,追加写)

    w+   (不存在则创建;存在则清空内容,覆盖写)与影响“光标”

    a+      同a

    文件内光标移动都是以字节为单位如seek,tell,truncate(rb.wb,ab)

    注意:

      seek(offset,from)

      offest:偏移量

      from:方向

      

      1. seek有三种移动方式0(文件开头),1(当前位置),2(文件末尾),其中1和2必须在b模式下进行,但无论哪种模式,都是以bytes为单位移动的

      2. truncate是截断文件,所以文件的打开方式必须可写,但是不能用w或w+等方式打开,因为那样直接清空文件了,所以truncate要在r+或a或a+等模式下测试效果

      3 tell是打印光标所在位置

     

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

      rb

      wb

      ab

     

    file操作的源码解析

     

    class file(object):
    
          def close(self): # real signature unknown; restored from __doc__
            关闭文件
    
            """close() -> None or (perhaps) an integer.  Close the file.
           
            Sets data attribute .closed to True.  A closed file cannot be used for
            further I/O operations.  close() may be called more than once without
            error.  Some kinds of file objects (for example, opened by popen())
            may return an exit status upon closing.
            """
     
         def fileno(self): # real signature unknown; restored from __doc__
            文件描述符   
    
             """fileno() -> integer "file descriptor".
            
            This is needed for lower-level file interfaces, such os.read(). """
            
            return 0    
    
        def flush(self): # real signature unknown; restored from __doc__
            刷新文件内部缓冲区
            
            """ flush() -> None.  Flush the internal I/O buffer. """
    
            pass
    
        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
    
        def next(self): # real signature unknown; restored from __doc__
            获取下一行数据,不存在,则报错
    
            """ x.next() -> the next value, or raise StopIteration """
    
            pass
    
     
    
        def read(self, size=None): # real signature unknown; restored from __doc__
            读取指定字节数据
    
            """read([size]) -> read at most size bytes, returned as a string.
          
            If the size argument is negative or omitted, read until EOF is reached.
            Notice that when in non-blocking mode, less data than what was requested
            may be returned, even if no size parameter was given."""
    
            pass
    
        def readinto(self): # real signature unknown; restored from __doc__
            读取到缓冲区,不要用,将被遗弃
    
            """ readinto() -> Undocumented.  Don't use this; it may go away. """
    
            pass
    
     
        def readline(self, size=None): # real signature unknown; restored from __doc__
            仅读取一行数据
            """readline([size]) -> next line from the file, as a string.
        
            Retain newline.  A non-negative size argument limits the maximum
            number of bytes to return (an incomplete line may be returned then).
            Return an empty string at EOF. """
    
            pass
    
        def readlines(self, size=None): # real signature unknown; restored from __doc__
            读取所有数据,并根据换行保存值列表
    
            """readlines([size]) -> list of strings, each a line from the file.         
    
            Call readline() repeatedly and return a list of the lines so read.
            The optional size argument, if given, is an approximate bound on the
            total number of bytes in the lines returned. """
    
            return []
    
     
    
        def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
            指定文件中指针位置
            """seek(offset[, whence]) -> None.  Move to new file position.
           
            Argument offset is a byte count.  Optional argument whence defaults to
            0 (offset from start of file, offset should be >= 0); other values are 1
            (move relative to current position, positive or negative), and 2 (move
            relative to end of file, usually negative, although many platforms allow
            seeking beyond the end of a file).  If the file is opened in text mode,
            only offsets returned by tell() are legal.  Use of other offsets causes
            undefined behavior.
            Note that not all file objects are seekable. """
    
            pass
    
     
    
        def tell(self): # real signature unknown; restored from __doc__
            获取当前指针位置
    
            """ tell() -> current file position, an integer (may be a long integer). """
            pass
    
    
        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
    
     
    
        def write(self, p_str): # real signature unknown; restored from __doc__
            写内容
    
            """write(str) -> None.  Write string str to file.
           
            Note that due to buffering, flush() or close() may be needed before
            the file on disk reflects the data written."""
    
            pass
    
        def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
            将一个字符串列表写入文件
            """writelines(sequence_of_strings) -> None.  Write the strings to the file.
    
             Note that newlines are not added.  The sequence can be any iterable object
             producing strings. This is equivalent to calling write() for each string. """
    
            pass
    
     
    
        def xreadlines(self): # real signature unknown; restored from __doc__
            可用于逐行读取文件,非全部
    
            """

         xreadlines() -> returns self. For backward compatibility. File objects now include the performance optimizations previously implemented in the xreadlines module.     """ def writable(self, *args, **kwargs): # real signature unknown 判断文件是否可写 def seekable(self, *args, **kwargs): # real signature unknown 判断文件是否可进行seek操作 def readable(self, *args, **kwargs): # real signature unknown 判断是否可读 def fileno(self, *args, **kwargs): # real signature unknown 返回文件句柄在内核中的索引值,以后做IO多路复用时可以用到

     详细:http://www.runoob.com/python/python-files-io.html

     

    eval()函数十分强大,官方demo解释为:将字符串str当成有效的表达式来求值并返回计算结果。

    so,结合math当成一个计算器很好用。

    其他用法,可以把list,tuple,dict和string相互转化。见下例子:

     1 a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"  
     2   
     3 b = eval(a)  
     4   
     5 b  
     6 Out[3]: [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]  
     7   
     8 type(b)  
     9 Out[4]: list  
    10   
    11 a = "{1: 'a', 2: 'b'}"  
    12   
    13 b = eval(a)  
    14   
    15 b  
    16 Out[7]: {1: 'a', 2: 'b'}  
    17   
    18 type(b)  
    19 Out[8]: dict  
    20   
    21 a = "([1,2], [3,4], [5,6], [7,8], (9,0))"  
    22   
    23 b = eval(a)  
    24   
    25 b  
    26 Out[11]: ([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))  

     

     

     

        

     

  • 相关阅读:
    通过xshell在本地win主机和远程linux主机传输文件
    CentOS7.4搭建ftp服务
    CentOS7.4中配置jdk环境
    spring AOP学习笔记
    java代码连接oracle数据库的方法
    通过xshell上传和下载文件
    java设计模式简述
    本地项目文件通过git提交到GitHub上
    centos7中oracle数据库安装和卸载
    centos7远程服务器中redis的安装与java连接
  • 原文地址:https://www.cnblogs.com/zqxqx/p/8067969.html
Copyright © 2020-2023  润新知