• Python运维开发之路《文件处理》


    一、python字典操作

    1.字典的定义

      字典一种key-value的数据类型,类似于json串。

    2.字典的特性

    key:value
    字典不可变,key唯一
    key的定义规则:
    1.不可变,数字、字符串、字典、元组(定义符合(),与列表完全一致,唯一不同的是元组内元素不可变)
    2.key必须是唯一的,所以字典天生有去重功能
    
    value的定义规则:
    1.任意数据类型

    3.字典的使用方法

      字典的增、删、改、查

     1 查询:
     2 print(dic['name'])
     3 print(dic.get('name'))    #get方法查询不存在的项不会报错
     4 
     5 添加:
     6 dic['gender'] = 'female'    #k:v 无序添加
     7 
     8 修改:
     9 dic['name'] = '11'  #key不可修改
    10 
    11 删除:
    12 del     #万能删除
    13 del dic['name'] #删除key

      其他使用方法和函数调用

    dicl = dict.fromkeys()  #快速生成字典
    dic.copy()          #浅拷贝,只拷贝一层
    dic.get()           #值不存在不会报错
    dic.items()         #打印转换为列表形式
    dic.keys()          #取出字典中所有的key值
    dic.pop()           #pop删除,括号内写key,key不存在会报错
    dic.popitem()       #随机删除一对key.val
    dic.setdefault()    #添加字典
    dic.update()        #添加新字典,添加字典内容,修改字典内容
    dic.values()        #取出字典所有values值

       字典的定义方法

    字典的定义方法:
    dic = dict()                            #空字典
    dic1 = dict({'name':'alex','age':18})
    print(dic1)
    dic2 = dict(name='alex',age=18)
    print(dic2)
    dic3 = dict((('name','alex'),('age','18')))
    print(dic3)

    二、集合

    1.集合的介绍 

      集合是一个无序的,不重复的数据组合,它的主要作用如下:

    • 去重,把一个列表变成集合,就自动去重了
    • 关系测试,测试两组数据之前的交集、差集、并集等关系

    2.集合的操作方法

    增加      add        #添加元素到集合
             update      #添加集合到集合
    
    随机删除    pop       #随机删除
               remove    #指定删除,如果删除元素不存在,程序报错
               discard   #指定删除,如果删除元素不存在,报none
    
    清空
            clear       #清空
    
    差集并赋值
            symmetric_difference_update #差集后,赋予新值

      集合的几种模式

    - 交集:intersection    print(s1&s2)
    - 并集:union       print(s1|s2)
    - 差集:difference  print(s1-s2)        
    - 子集:issubset    print(s1<=s2)
    - 父集:issuperset  print(s1>=s2)
    - 对称差集:symmetric_difference    print(s1^s2)    #去掉两个集合里重复的

    三、字符编码

    1.在python2默认编码是ASCII, python3里默认是utf-8

    2.unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-8就是unicode

    3.在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string

    4.内存固定使用Unicode编码,硬盘的编码可以修改(即可以修改的软件编码)

    5.使用什么编码往硬盘存,就用什么编码去读

    6.程序运行分两个阶段:

      - 从硬盘读到内存

      - python解释器运行读到内存里的代码

    7.针对.py文件,python与nodpad++vim的区别是多了运行已经读到内存里的代码

    四、python文件处理

    1.关于python循环读取数据

    文本文件:

     1 Somehow, it seems the love I knew was always the most destructive kind
     2 不知为何,我经历的爱情总是最具毁灭性的的那种
     3 Yesterday when I was young
     4 昨日当我年少轻狂
     5 The taste of life was sweet
     6 生命的滋味是甜的
     7 As rain upon my tongue
     8 就如舌尖上的雨露
     9 I teased at life as if it were a foolish game
    10 我戏弄生命 视其为愚蠢的游戏
    11 The way the evening breeze
    12 就如夜晚的微风
    13 May tease the candle flame
    14 逗弄蜡烛的火苗
    15 The thousand dreams I dreamed
    16 我曾千万次梦见
    17 The splendid things I planned
    18 那些我计划的绚丽蓝图
    19 I always built to last on weak and shifting sand
    20 但我总是将之建筑在易逝的流沙上
    21 I lived by night and shunned the naked light of day
    22 我夜夜笙歌 逃避白昼赤裸的阳光
    23 And only now I see how the time ran away
    24 事到如今我才看清岁月是如何匆匆流逝
    25 Yesterday when I was young
    26 昨日当我年少轻狂
    27 So many lovely songs were waiting to be sung
    28 有那么多甜美的曲儿等我歌唱
    29 So many wild pleasures lay in store for me
    30 有那么多肆意的快乐等我享受
    31 And so much pain my eyes refused to see
    32 还有那么多痛苦 我的双眼却视而不见
    33 I ran so fast that time and youth at last ran out
    34 我飞快地奔走 最终时光与青春消逝殆尽
    35 I never stopped to think what life was all about
    36 我从未停下脚步去思考生命的意义
    37 And every conversation that I can now recall
    38 如今回想起的所有对话
    39 Concerned itself with me and nothing else at all
    40 除了和我相关的 什么都记不得了
    41 The game of love I played with arrogance and pride
    42 我用自负和傲慢玩着爱情的游戏
    43 And every flame I lit too quickly, quickly died
    44 所有我点燃的火焰都熄灭得太快
    45 The friends I made all somehow seemed to slip away
    46 所有我交的朋友似乎都不知不觉地离开了
    47 And only now I'm left alone to end the play, yeah
    48 只剩我一个人在台上来结束这场闹剧
    49 Oh, yesterday when I was young
    50 噢 昨日当我年少轻狂
    51 So many, many songs were waiting to be sung
    52 有那么那么多甜美的曲儿等我歌唱
    53 So many wild pleasures lay in store for me
    54 有那么多肆意的快乐等我享受
    55 And so much pain my eyes refused to see
    56 还有那么多痛苦 我的双眼却视而不见
    57 There are so many songs in me that won't be sung
    58 我有太多歌曲永远不会被唱起
    59 I feel the bitter taste of tears upon my tongue
    60 我尝到了舌尖泪水的苦涩滋味
    61 The time has come for me to pay for yesterday
    62 终于到了付出代价的时间 为了昨日
    63 When I was young
    64 当我年少轻狂
    lyrics

    读取文件前5行:

    #-*- coding:utf-8 -*-
    data = open("lyrics",encoding='UTF-8')
    
    ##循环打印readlines,占用内存空间不推荐
    for index,line in enumerate(data.readlines()):
        if index < 5:
            print(line)
        else:
            break
    
    ##循环打印readline
    for i in range(5):
        print(data.readline().strip())
    
    ##循环打印for
    count = 0
    for line in data:
        if count < 5:
            print(line.strip())
            count +=1
        else:
            break

     2.python文件处理命令用法

    基本的文件模式

     1 #r,读模式,open命令默认是读模式
     2 f = open('testfile','r',encoding='utf-8')
     3 print(f.read())
     4 
     5 #w,写模式
     6 f = open('testfile','w',encoding='utf-8')
     7 f.write('人生苦短,我学python
    ')
     8 f.close()
     9 
    10 #a,追加模式
    11 f = open('testfile','a',encoding='utf-8')
    12 f.write('我呵呵你!
    ')
    13 f.close()
    14 
    15 #删除,打开一个文件写入空即删除
    16 f = open('testfile','r+',encoding='utf-8')
    17 f.readline()
    18 f.write('')
    19 
    20 #r+,读写 可读,追加内容到最后
    21 f = open('testfile','r+',encoding='utf-8')
    22 f.readline()
    23 f.write('devops
    ')
    24 
    25 #w+,写读  新建文件,写入再读取
    26 f = open('testfile','w+',encoding='utf-8')
    27 f.readline()
    28 f.write('devops2
    ')
    29 
    30 # a+,追加读 清空源文件,再添加,然后读取
    31 f = open('testfile','w+',encoding='utf-8')
    32 f.readline()
    33 f.write('devops3
    ')

    其他文件操作方法

    f = open('testfile','w+',encoding='utf-8')
    f.close()
    
    f.closed    #判断操作的文件是否关闭
    f.encoding  #打印文件的编码格式
    f.fileno()  #返回操作系统接口文件索引<网络编程,I/O复用>
    f.flush()   #刷新操作
    f.isatty()  #判断打开的文件是否是终端文件
    f.name      #打印文件名
    f.newlines  #未读取到行分隔符时为 None,只有一种行分隔符时为一个字符串,当文件有多种类型的行结束符时,则为一个包含所有当前所遇到的行结束符的列表
    f.readable()    #同isatty类似
    f.seek()    #移动光标,到固定位置返回此位置以后的内容(按照字符移)
    f.tell()    #打印光标所在位置的索引
    f.truncate()    #截断,配合seek,括号内指定保留字符数量,从头开始切
    f.writelines()  #写列表到文件
     1 def close(self): # real signature unknown; restored from __doc__
     2         """
     3         Close the file.
     4         
     5         A closed file cannot be used for further I/O operations.  close() may be
     6         called more than once without error.
     7         """
     8         pass
     9 
    10     def fileno(self, *args, **kwargs): # real signature unknown
    11         """ Return the underlying file descriptor (an integer). """
    12         pass
    13 
    14     def isatty(self, *args, **kwargs): # real signature unknown
    15         """ True if the file is connected to a TTY device. """
    16         pass
    17 
    18     def read(self, size=-1): # known case of _io.FileIO.read
    19         """
    20         注意,不一定能全读回来
    21         Read at most size bytes, returned as bytes.
    22         
    23         Only makes one system call, so less data may be returned than requested.
    24         In non-blocking mode, returns None if no data is available.
    25         Return an empty bytes object at EOF.
    26         """
    27         return ""
    28 
    29     def readable(self, *args, **kwargs): # real signature unknown
    30         """ True if file was opened in a read mode. """
    31         pass
    32 
    33     def readall(self, *args, **kwargs): # real signature unknown
    34         """
    35         Read all data from the file, returned as bytes.
    36         
    37         In non-blocking mode, returns as much as is immediately available,
    38         or None if no data is available.  Return an empty bytes object at EOF.
    39         """
    40         pass
    41 
    42     def readinto(self): # real signature unknown; restored from __doc__
    43         """ Same as RawIOBase.readinto(). """
    44         pass #不要用,没人知道它是干嘛用的
    45 
    46     def seek(self, *args, **kwargs): # real signature unknown
    47         """
    48         Move to new file position and return the file position.
    49         
    50         Argument offset is a byte count.  Optional argument whence defaults to
    51         SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
    52         are SEEK_CUR or 1 (move relative to current position, positive or negative),
    53         and SEEK_END or 2 (move relative to end of file, usually negative, although
    54         many platforms allow seeking beyond the end of a file).
    55         
    56         Note that not all file objects are seekable.
    57         """
    58         pass
    59 
    60     def seekable(self, *args, **kwargs): # real signature unknown
    61         """ True if file supports random-access. """
    62         pass
    63 
    64     def tell(self, *args, **kwargs): # real signature unknown
    65         """
    66         Current file position.
    67         
    68         Can raise OSError for non seekable files.
    69         """
    70         pass
    71 
    72     def truncate(self, *args, **kwargs): # real signature unknown
    73         """
    74         Truncate the file to at most size bytes and return the truncated size.
    75         
    76         Size defaults to the current file position, as returned by tell().
    77         The current file position is changed to the value of size.
    78         """
    79         pass
    80 
    81     def writable(self, *args, **kwargs): # real signature unknown
    82         """ True if file was opened in a write mode. """
    83         pass
    84 
    85     def write(self, *args, **kwargs): # real signature unknown
    86         """
    87         Write bytes b to file, return number written.
    88         
    89         Only makes one system call, so not all of the data may be written.
    90         The number of bytes actually written is returned.  In non-blocking mode,
    91         returns None if the write would block.
    92         """
    93         pass
    python2中源码解释

    本文来自博客园,作者:白日梦想家Zz,转载请注明原文链接:https://www.cnblogs.com/zzlain/p/6005089.html

  • 相关阅读:
    ext之Windows
    多个DIV显示/隐藏
    asp.net 得到上一页地址
    人们的文化和素质
    gridview 删除问题
    RSS of the Day: 新闻类Feeds
    每日英语:Taiwan Tech Firms Bring Jobs Home Quietly
    每日英语:Freedom and America's gun culture
    matlab学习:图像频域分析之Gabor滤波
    每日英语:The End Of The World Is (Not) Nigh
  • 原文地址:https://www.cnblogs.com/zzlain/p/6005089.html
Copyright © 2020-2023  润新知