• 浅谈自学Python之路(day3)


    今天的主要内容是:

    文件操作

    对文件操作的流程:

    • 打开文件,得到文件句柄并赋值给一个变量
    • 通过句柄对文件进行操作
    • 关闭文件

    现有文件如下:

    tonghuazhen
    听说白雪公主在逃跑
    小红帽在担心大灰狼
    听说疯帽喜欢爱丽丝
    丑小鸭会变成白天鹅
    听说彼得潘总长不大
    杰克他有竖琴和魔法
    听说森林里有糖果屋
    灰姑娘丢了心爱的玻璃鞋
    只有睿智的河水知道
    白雪是因为贪玩跑出了城堡
    小红帽有件抑制自己
    变成狼的大红袍
    总有一条蜿蜒在童话镇里七彩的河
    沾染魔法的乖张气息
    却又在爱里曲折
    川流不息扬起水花
    又卷入一帘时光入水
    让所有很久很久以前
    都走到幸福结局的时刻
    View Code

    打开文件的模式有:

    • r,只读模式(默认)。
    • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
    • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

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

    • r+,可读写文件。【可读;可写;可追加】
    • w+,写读
    • a+,同a

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

    • rU
    • r+U

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

    • rb
    • wb
    • ab

    知道了以上的模式后,现在就来进入我们的操作:

    • read:读
    1 f = open("yesterday","r",encoding="utf-8")#文件句柄  [文件名/操作首字母/字符编码]
    2 #r = read 读
    3 
    4 data = f.read()
    5 print(data)
    6 f.close()
    • write:写
    1 f = open("yesterday","w",encoding="utf-8")#文件句柄  [文件名/操作首字母/字符编码]
    2 #w = write 写  重新创建新文档,如果文档名称有重复则覆盖原文档
    3 
    4 f.write("
    人心无可填
    ")
    5 f.write("河水太浅,怎托得起,岁月的积淀")
    6 f.close()
    • append:追加
    1 f = open("yesterday2","a",encoding="utf-8")#文件句柄  [文件名/操作首字母/字符编码]
    2 #a = append 追加  只能追加,不能读
    3 
    4 f.write("
    人心无可填......
    ")
    5 f.write("河水太浅,怎托得起,岁月的积淀........")
    6 f.close()
    • 读前五行代码:
    1 f = open("yesterday","r",encoding="utf-8")#文件句柄  [文件名/操作首字母/字符编码]
    2 
    3 #读前五行
    4 print(f.readline())
    5 print(f.readline())
    6 print(f.readline())
    7 print(f.readline())
    8 print(f.readline())
    • 用循环写前五行代码:
    1 #读前五行
    2 for i in range(5):
    3     print(f.readline())
    
    • 将其变为列表格式输出:
    1 print(f.readlines())#变为列表,每一行是一个元素

    输出结果为:

    这就是列表的格式

    • 如果用循环输出这个列表:
    1 #循环列表
    2 for line in f.readlines():
    3     print(line.strip())#   .strip()空格和换行都去掉

    这里用到了Python strip()方法:

    描述

    Python strip() 方法用于移除字符串头尾指定的字符(默认为空格)。

    语法

    strip()方法语法:

    str.strip([chars]);
    • 打印文档中的前十行:
    1 #打印前10行 , f.readlines()只适合读小文件
    2 for index,line in enumerate(f.readlines()):
    3     if index == 9:
    4         print("这是一条分割线".center(50,"-"))
    5         continue
    6     print(line.strip())

    但这方法只适合打印小文件,如果数据较大我们用下面这种方法:

    1 count = 0
    2 for line in f:
    3     if count == 9:
    4         print("---分割线---")
    5         count += 1
    6         continue
    7     print(line)
    8     count += 1

    输出结果为:

     其它语法:

    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
    
        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 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 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 readinto(self): # real signature unknown; restored from __doc__
            """ Same as RawIOBase.readinto(). """
            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 seekable(self, *args, **kwargs): # real signature unknown
            """ True if file supports random-access. """
            pass
    
        def tell(self, *args, **kwargs): # real signature unknown
            """
            Current file position.
            
            Can raise OSError for non seekable files.
            """
            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 writable(self, *args, **kwargs): # real signature unknown
            """ True if file was opened in a write mode. """
            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
    View Code

    如果,您认为阅读这篇博客让您有些收获,不妨点击一下右下角的推荐按钮。
    如果,您希望更容易地发现我的新博客,不妨点击一下绿色通道的关注我

    我的写作热情离不开您的肯定支持,感谢您的阅读,我是【YMLiang】!

    我的个人博客:https://ymliang.netlify.com

    QQ:616581760

    邮箱:616581760@qq.com

  • 相关阅读:
    Excel 2007中忘记保护工作表密码的解决
    厦门高崎机场Wifi测试
    Windows 7下无法使用NetMeeting的共享功能的解决
    使用Winacq获取磁盘镜像
    USB 3.0 Test
    Tips:Windows 7的应用程序兼容性和絮叨的应用程序兼容性助手
    The requested resource is in use的解决方法
    运行时创建HTTP请求及请求的处理
    XML操作示例
    iframe自动适应页面
  • 原文地址:https://www.cnblogs.com/cxylff/p/8521938.html
Copyright © 2020-2023  润新知