zoukankan      html  css  js  c++  java
  • Python的文件操作

    文件操作,顾名思义,就是对磁盘上已经存在的文件进行各种操作,文本文件就是读和写。

    1. 文件的操作流程

    (1)打开文件,得到文件句柄并赋值给一个变量

    (2)通过句柄对文件进行操作

    (3)关闭文件

    现有文件

    1 昔闻洞庭水,今上岳阳楼。
    2 吴楚东南坼,乾坤日夜浮。
    3 亲朋无一字,老病有孤舟。
    4 戎马关山北,凭轩涕泗流。

    2. 文件的打开模式

    打开文件的模式:

    三种基本模式:

    1. r,只读模式(默认)

    2. w,只写模式。(不可读,不存在文件则创建,存在则删除内容)

    3. a,追加模式。(不存在文件则创建,存在则在文件末尾追加内容)

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

    4.r+,可读写。(读文件从文件起始位置,写文件则跳转到文件末尾添加)

    5.w+,可写读。(文件不存在就创建文件,文件存在则清空文件,之后可写可读)

    6.a+,可读写,读和写都从文件末尾开始。

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

    7.rU

    8.r+U

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

    9. rb

    10.wb

    11.ab

    3.文件具体操作

    def read(self, size=-1): # known case of _io.FileIO.read
            """
            注意,不一定能全读回来
            Read at most size bytes, returned as bytes.
    
            Only makes one system call, so less data may be returned than requested.
            In non-blocking mode, returns None if no data is available.
            Return an empty bytes object at EOF.
            """
            return ""
    
    def readline(self, *args, **kwargs):
            pass
    
    def readlines(self, *args, **kwargs):
            pass
    
    
    def tell(self, *args, **kwargs): # real signature unknown
            """
            Current file position.
    
            Can raise OSError for non seekable files.
            """
            pass
    
    def seek(self, *args, **kwargs): # real signature unknown
            """
            Move to new file position and return the file position.
    
            Argument offset is a byte count.  Optional argument whence defaults to
            SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
            are SEEK_CUR or 1 (move relative to current position, positive or negative),
            and SEEK_END or 2 (move relative to end of file, usually negative, although
            many platforms allow seeking beyond the end of a file).
    
            Note that not all file objects are seekable.
            """
            pass
    
    def write(self, *args, **kwargs): # real signature unknown
            """
            Write bytes b to file, return number written.
    
            Only makes one system call, so not all of the data may be written.
            The number of bytes actually written is returned.  In non-blocking mode,
            returns None if the write would block.
            """
            pass
    
    def flush(self, *args, **kwargs):
            pass
    
    
    def truncate(self, *args, **kwargs): # real signature unknown
            """
            Truncate the file to at most size bytes and return the truncated size.
    
            Size defaults to the current file position, as returned by tell().
            The current file position is changed to the value of size.
            """
            pass
    
    
    def close(self): # real signature unknown; restored from __doc__
                """
                Close the file.
    
                A closed file cannot be used for further I/O operations.  close() may be
                called more than once without error.
                """
                pass
    ##############################################################less usefull
        def fileno(self, *args, **kwargs): # real signature unknown
                """ Return the underlying file descriptor (an integer). """
                pass
    
        def isatty(self, *args, **kwargs): # real signature unknown
            """ True if the file is connected to a TTY device. """
            pass
    
        def readable(self, *args, **kwargs): # real signature unknown
            """ True if file was opened in a read mode. """
            pass
    
        def readall(self, *args, **kwargs): # real signature unknown
            """
            Read all data from the file, returned as bytes.
    
            In non-blocking mode, returns as much as is immediately available,
            or None if no data is available.  Return an empty bytes object at EOF.
            """
            pass
    
        def seekable(self, *args, **kwargs): # real signature unknown
            """ True if file supports random-access. """
            pass
    
    
        def writable(self, *args, **kwargs): # real signature unknown
            """ True if file was opened in a write mode. """
            pass
    
    操作方法介绍
    具体操作
     1 open()打开文件
     2 close()关闭文件
     3 
     4 f = open('登岳阳楼','r')
     5 print(f.read()) #读取所有
     6 >>>
     7 昔闻洞庭水,今上岳阳楼。
     8 吴楚东南坼,乾坤日夜浮。
     9 亲朋无一字,老病有孤舟。
    10 戎马关山北,凭轩涕泗流
    11 
    12 print(f.read(5))  #读取5个字
    13 >>>
    14 昔闻洞庭水
    15 
    16 print(f.readline()) #读取一行
    17 print(f.readline()) #继续执行,读取下一行
    18 >>>
    19 昔闻洞庭水,今上岳阳楼。
    20 
    21 吴楚东南坼,乾坤日夜浮。
    22 
    23 print(f.readlines())  #以列表形式读出文件
    24 >>>
    25 ['昔闻洞庭水,今上岳阳楼。
    ', '吴楚东南坼,乾坤日夜浮。
    ', '亲朋无一字,老病有孤舟。
    ', '戎马关山北,凭轩涕泗流。']
    26 for i in f.readlines():
    27     print(i)
    28 >>>
    29 昔闻洞庭水,今上岳阳楼。
    30 
    31 吴楚东南坼,乾坤日夜浮。
    32 
    33 亲朋无一字,老病有孤舟。
    34 
    35 戎马关山北,凭轩涕泗流。
    36 还可以用:(建议这种方法)
    37 for i in f:
    38     print(i)
    39     
    40 print(f.tell()) #指出光标所在位置r模式打开文件默认光标在初始位置0
    41 >>>
    42 0
    43 
    44 f = open('登岳阳楼','r',encoding='utf-8')
    45 print(f.tell())
    46 f.seek(5)
    47 print(f.tell())
    48 >>>
    49 0
    50 5
    51 f.seek() 用于调整光标位置类似于下载时的断线重连
    52 
    53 f = open('登岳阳楼','w',encoding='utf-8')
    54 f.write('hello world')
    55 >>>
    56 hello world
    57 #用w模式打开文件将会清除文件所有内容,再添加write()中的内容
    58 
    59 f.flush()  #写文件时,写的内容不会直接写到文件中,而是保存在内存里,等文件close后才写入文件,flush()方法就是将内存中的内容立刻写入文件。可用于进度条
    60 
    61 f = open('登岳阳楼','w',encoding='utf-8')
    62 f.write('hello world')
    63 f.truncate(4)   #截断内容
    64 >>>
    65 hell

    with语句

    为了防止我们在对文件操作后忘记close()文件,可以通过with语句对文件操作,

    1 with open('登岳阳楼','r',encoding='utf-8') as f:
    2     print(f.read())
    3 >>>
    4 昔闻洞庭水,今上岳阳楼。
    5 吴楚东南坼,乾坤日夜浮。
    6 亲朋无一字,老病有孤舟。
    7 戎马关山北,凭轩涕泗流。

    当with语句执行完毕,文件就默认关闭了。

  • 相关阅读:
    剑指 Offer 31. 栈的压入、弹出序列
    【笔记】小样本学习(Few-shot Learning)(1)
    【VS】Visual Studio 自带的反编译工具,方便了太多了。
    秋招提前批已来,万字长文教你如何增加面试大厂的成功率🔥
    Spring Boot自动配置原理与实践(二)
    MySQL是怎么解决幻读问题的?
    深入学习Netty(5)——Netty是如何解决TCP粘包/拆包问题的?
    深入学习Netty(4)——Netty编程入门
    HttpRunner3.X
    HttpRunner3.X
  • 原文地址:https://www.cnblogs.com/hujq1029/p/5811518.html
Copyright © 2011-2022 走看看