• Python 基础之-数据类型


    本节内容

    1. 列表与字典
    2. 字符串
    3. 集合
    4. 元组
    5. 文件

    1. 列表与字典

          列表与字典这两个对象类型都是其他对象的集合。这两种类型几乎是Python所有脚本的主要工作组件。它们都可以在原处进行修改,也可以按需增长或缩短,而且可以包含任何种类的对象或者或者或者被嵌套。借助这些类型,可以在脚本中创建并处理任意的复杂的信息结构。

    列表

    列表是Python中最具灵活性的有序集合对象类型,而且是我们以后最常用的数据类型之一。通过列表可以对数据实现最方便的存储,修改等操作。

    定义列表

    >>> names = ['ZhangSan','LiSi','WangWu']

    基本列表操作

    >>> names
    ['ZhangSan', 'LiSi', 'WangWu']
    >>> len(names)        #计算列表长度
    3
    >>> names[0]        #访问列表中的元素,下标从0开始计数
    'ZhangSan'
    >>> names[2]
    'WangWu'
    >>> names[-1]        #还可以倒着取
    'WangWu'
    >>> names[-2]
    'LiSi'
    >>> 'WangWu' in names        #检查元素是否在列表中
    True
    >>> names + ['ZhaoLiu','SunQi','ZhouBa']        #列表合并
    ['ZhangSan', 'LiSi', 'WangWu', 'ZhaoLiu', 'SunQi', 'ZhouBa']
    >>> names        #原始列表并不会发生改变
    ['ZhangSan', 'LiSi', 'WangWu']
    >>> names * 3        #列表重复
    ['ZhangSan', 'LiSi', 'WangWu', 'ZhangSan', 'LiSi', 'WangWu', 'ZhangSan', 'LiSi', 'WangWu']
    >>> names
    ['ZhangSan', 'LiSi', 'WangWu']

     分片和矩阵

    >>> names = ['ZhangSan','LiSi','WangWu','ZhaoLiu','SunQi','ZhouBa','WuJiu']
    >>> names[4:1]        #切片是按照从左往右取的,不能倒着取
    []
    >>> names[1:4]     #取下标1至下标4之间的数字,包括1,不包括4
    ['LiSi', 'WangWu', 'ZhaoLiu']
    >>> names[1:-1]     #取下标1至-1的值,不包括-1
    ['LiSi', 'WangWu', 'ZhaoLiu', 'SunQi', 'ZhouBa']
    >>> names[0:3]
    ['ZhangSan', 'LiSi', 'WangWu']
    >>> names[:3]     #如果是从头开始取,0可以忽略,跟上句效果一样
    ['ZhangSan', 'LiSi', 'WangWu']
    >>> names[3:]     #如果想取最后一个,必须不能写-1,只能这么写
    ['ZhaoLiu', 'SunQi', 'ZhouBa', 'WuJiu']
    >>> names[3:-1]     #这样-1就不会被包含了
    ['ZhaoLiu', 'SunQi', 'ZhouBa']
    >>> names[0::2]     #后面的2是代表,每隔一个元素,就取一个
    ['ZhangSan', 'WangWu', 'SunQi', 'WuJiu']
    >>> names[::2]     #和上句效果一样
    ['ZhangSan', 'WangWu', 'SunQi', 'WuJiu']
    
    >>> names = [['ZhangSan','LiSi'],['WangWu','ZhaoLiu'],['SunQi','ZhouBa','WuJiu']]
    >>> names[1]
    ['WangWu', 'ZhaoLiu']
    >>> names[1][1]     #嵌套索引
    'ZhaoLiu'
    >>> names[2][0]
    'SunQi'
    >>> names[2][2]
    'WuJiu'
    View Code

    追加

    >>> names
    ['ZhangSan', 'LiSi', 'WangWu', 'ZhaoLiu', 'SunQi', 'ZhouBa', 'WuJiu']
    >>> names.append('按照顺序排到最后位置')
    >>> names
    ['ZhangSan', 'LiSi', 'WangWu', 'ZhaoLiu', 'SunQi', 'ZhouBa', 'WuJiu', '按照顺序排到最后位置']
    View Code

    插入

    >>> names
    ['ZhangSan', 'LiSi', 'WangWu', 'ZhaoLiu', 'SunQi', 'ZhouBa', 'WuJiu', '按照顺序排到最后位置']
    >>> names.insert(2,'插队到第2个位置')
    >>> names
    ['ZhangSan', 'LiSi', '插队到第2个位置', 'WangWu', 'ZhaoLiu', 'SunQi', 'ZhouBa', 'WuJiu', '按照顺序排到最后位置']
    View Code

    修改

    >>> names
    ['ZhangSan', 'LiSi', '插队到第2个位置', 'WangWu', 'ZhaoLiu', 'SunQi', 'ZhouBa', 'WuJiu', '按照顺序排到最后位置']
    >>> names[3] = '第三个位置换人了'
    >>> names
    ['ZhangSan', 'LiSi', '插队到第2个位置', '第三个位置换人了', 'ZhaoLiu', 'SunQi', 'ZhouBa', 'WuJiu', '按照顺序排到最后位置']
    >>> names[5:7] = ['第五个位置换人了','第六个位置换人了']
    >>> names
    ['ZhangSan', 'LiSi', '插队到第2个位置', '第三个位置换人了', 'ZhaoLiu', '第五个位置换人了', '第六个位置换人了', 'WuJiu', '按照顺序排到最后位置']
    >>> names[2:4] = ['第二个和第三个位置的人离开了,新来的人插队到第二个位置']
    >>> names
    ['ZhangSan', 'LiSi', '第二个和第三个位置的人离开了,新来的人插队到第二个位置', 'ZhaoLiu', '第五个位置换人了', '第六个位置换人了', 'WuJiu', '按照顺序排到最后位置']
    View Code

    删除

    >>> names
    ['ZhangSan', 'LiSi', '第二个和第三个位置的人离开了,新来的人插队到第二个位置', 'ZhaoLiu', '第五个位置换人了', '第六个位置换人了', 'WuJiu', '按照顺序排到最后位置']
    >>> del names[2]
    >>> names
    ['ZhangSan', 'LiSi', 'ZhaoLiu', '第五个位置换人了', '第六个位置换人了', 'WuJiu', '按照顺序排到最后位置']
    >>> del names[3:5]     #删除第三个和第四个元素
    >>> names
    ['ZhangSan', 'LiSi', 'ZhaoLiu', 'WuJiu', '按照顺序排到最后位置']
    >>> names.remove('ZhaoLiu')     #删除指定元素
    >>> names
    ['ZhangSan', 'LiSi', 'WuJiu', '按照顺序排到最后位置']
    >>> names.pop()     #删除列表最后一个值
    '按照顺序排到最后位置'
    >>> names
    ['ZhangSan', 'LiSi', 'WuJiu']
    >>> names.pop(1)     #指定列表索引值,删除指定元素
    'LiSi'
    >>> names
    ['ZhangSan', 'WuJiu']
    >>> names[1:] = []     #删除第一个及后面所有元素
    >>> names
    ['ZhangSan']
    >>> names.clear()        #清空整个列表
    >>> names
    []
    View Code

     扩展

    >>> names
    ['ZhangSan']
    >>> L = ['李四','王五','赵六']
    >>> names.extend(L)
    >>> names
    ['ZhangSan', '李四', '王五', '赵六']
    View Code

     拷贝

    ##    浅拷贝
    >>> names = ['ZhangSan', 'LiSi', [1,2,3], 'WangWu', 'ZhouLiu', 'SunQi']
    >>> names_copy = names.copy()
    >>> names_copy
    ['ZhangSan', 'LiSi', [1, 2, 3], 'WangWu', 'ZhouLiu', 'SunQi']
    >>> names_copy[1] = 'TengBb'
    >>> names
    ['ZhangSan', 'LiSi', [1, 2, 3], 'WangWu', 'ZhouLiu', 'SunQi']
    >>> names_copy
    ['ZhangSan', 'TengBb', [1, 2, 3], 'WangWu', 'ZhouLiu', 'SunQi']
    
    >>> names_copy[2][0] = 100
    >>> names
    ['ZhangSan', 'LiSi', [100, 2, 3], 'WangWu', 'ZhouLiu', 'SunQi']
    >>> names_copy
    ['ZhangSan', 'TengBb', [100, 2, 3], 'WangWu', 'ZhouLiu', 'SunQi']
    
    #从上述结果可以看出,names.copy()复制出一个与names列表一样的列表当修改列表中的内容时,如果列表中嵌套有列表,那么如果修改是列表的第一层,那么只会更改修改的那个列表,如果修改的是嵌套里的列表的内容,则两个列表的内容的都会更改
    
    
    ##    深拷贝
    >>> import copy
    >>> names = ['ZhangSan', 'LiSi', [1,2,3], 'WangWu', 'ZhouLiu', 'SunQi']
    >>> names_copy = copy.deepcopy(names)
    >>> names_copy
    ['ZhangSan', 'LiSi', [1, 2, 3], 'WangWu', 'ZhouLiu', 'SunQi']
    >>> names_copy[2][0] = 100
    >>> names
    ['ZhangSan', 'LiSi', [1, 2, 3], 'WangWu', 'ZhouLiu', 'SunQi']
    >>> names_copy
    ['ZhangSan', 'LiSi', [100, 2, 3], 'WangWu', 'ZhouLiu', 'SunQi']
    
    #如上结果所示,深拷贝的时候,就是完全都开辟出另外一个内存空间,及修改其中一个列表中任意一个值,另外一个列表都不会发生变化
    View Code

    统计

    >>> names
    ['ZhangSan', 'LiSi', 'WangWu', 'ZhangSan', 'SunQi']
    >>> names.count('ZhangSan')
    2
    View Code

    排序&反转

    >>> names
    ['ZhangSan', 'LiSi', 'WangWu', 'ZhouLiu', 'SunQi', 1, 2, 3]
    >>> names.sort()     #排序
    Traceback (most recent call last):
      File "<pyshell#36>", line 1, in <module>
        names.sort()
    TypeError: '<' not supported between instances of 'int' and 'str'     #3.0里不同数据类型不能放在一起排序了
    >>> names[-3:] = ['1','2','3']
    >>> names
    ['LiSi', 'SunQi', 'WangWu', 'ZhangSan', 'ZhouLiu', '1', '2', '3']
    >>> names.sort()
    >>> names
    ['1', '2', '3', 'LiSi', 'SunQi', 'WangWu', 'ZhangSan', 'ZhouLiu']
    
    >>> names.reverse()     #反转
    >>> names
    ['ZhouLiu', 'ZhangSan', 'WangWu', 'SunQi', 'LiSi', '3', '2', '1']
    View Code

    还有其它方法可以实现排序!!

    获取下标

    >>> names
    ['ZhaoLiu', 'LiSi', 'WangWu', 'WangWu', 'SunQi']
    >>> names.index('WangWu')
    2          #只返回找到的第一个下标
    View Code

    字典

           除了列表以外,字典(dictionary)也许是Python之中最灵活的内置数据结构类型。如果把列表看作是有序的对象集合,那么就可以把字典当成是无序的集合。它们主要的差别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。

    字典是一种 key - value 的数据类型。语法如下所示:

    stu_info = {
        'stu01':'ZhangSan',
        'stu02':'LiSi',
        'stu03':'WangWu'
    } 

    注:字典的key不能是list类型

    字典的特性:

    • key-value格式,key是唯一的,天生去重
    • dict是无序的
    • 查询速度快
    >>> dict = {'b':2,'a':1,'b':5,'d':3,'a':6,'c':10}
    >>> dict
    {'b': 5, 'a': 6, 'd': 3, 'c': 10}     #去重

    字典的基本操作

    查找

    >>> stu_info
    {'stu01': 'ZhangSan', 'stu02': 'LiSi', 'stu03': 'WangWu'}
    >>> 'stu02' in stu_info     #标准用法
    True
    >>> stu_info.get('stu02')     #获取值
    'LiSi'
    >>> stu_info['stu02']     #同上,但是看下面
    'LiSi'
    >>> stu_info['stu05']     #如果一个key不存在,就报错,get不会,不存在只返回None,看下一个。
    Traceback (most recent call last):
      File "<pyshell#16>", line 1, in <module>
        stu_info['stu05']
    KeyError: 'stu05'
    >>> print(stu_info.get('stu05'))
    None
    >>> stu_info.get('stu05',88)     #如果要获取的key不存在,那么返回定义的值。如果存在则返回该key的值,看下一个。
    88
    >>> stu_info.get('stu02',88)
    'LiSi'
    View Code

     增加

    >>> stu_info
    {'stu01': 'ZhangSan', 'stu02': 'LiSi', 'stu03': 'WangWu'}
    >>> stu_info['stu04'] = '赵六'
    >>> stu_info
    {'stu01': 'ZhangSan', 'stu02': 'LiSi', 'stu03': 'WangWu', 'stu04': '赵六'}
    View Code

    修改

    >>> stu_info
    {'stu01': 'ZhangSan', 'stu02': 'LiSi', 'stu03': 'WangWu', 'stu04': '赵六'}
    >>> stu_info['stu01'] = '张三'
    >>> stu_info
    {'stu01': '张三', 'stu02': 'LiSi', 'stu03': 'WangWu', 'stu04': '赵六'}
    View Code

     删除

    >>> stu_info
    {'stu01': '张三', 'stu02': 'LiSi', 'stu03': 'WangWu', 'stu04': '赵六'}
    >>> stu_info.pop('stu01')    #删除指定值
    '张三'
    >>> stu_info
    {'stu02': 'LiSi', 'stu03': 'WangWu', 'stu04': '赵六'}
    >>> del stu_info['stu04']     #同上一个
    >>> stu_info
    {'stu02': 'LiSi', 'stu03': 'WangWu'}
    >>> stu_info.popitem()     #随机删除
    ('stu03', 'WangWu')
    >>> stu_info
    {'stu02': 'LiSi'}
    View Code

    其他用法

    >>> stu_info
    {'stu01': 'ZhangSan', 'stu02': 'LiSi', 'stu03': 'WangWu'}
    >>> list(stu_info.keys())     #返回字典的键列表,3.0中要用list调用来显示所有值
    ['stu01', 'stu02', 'stu03']
    >>> list(stu_info.values())     #返回字典的值列表
    ['ZhangSan', 'LiSi', 'WangWu']
    
    #设置默认值
    >>> stu_info.setdefault('stu04','ZhaoLiu')
    'ZhaoLiu'
    >>> stu_info
    {'stu01': 'ZhangSan', 'stu02': 'LiSi', 'stu03': 'WangWu', 'stu04': 'ZhaoLiu'}
    >>> stu_info.setdefault('stu01','张三')
    'ZhangSan'
    >>> stu_info
    {'stu01': 'ZhangSan', 'stu02': 'LiSi', 'stu03': 'WangWu', 'stu04': 'ZhaoLiu'}
    
    #update (把一个字典的键和值合并到另一个字典中,盲目地覆盖相同键的值)
    >>> stu_info
    {'stu01': 'ZhangSan', 'stu02': 'LiSi', 'stu03': 'WangWu', 'stu04': 'ZhaoLiu'}
    >>> b = {'a':1,'b':2,'c':3}
    >>> stu_info.update(b)
    >>> stu_info
    {'stu01': 'ZhangSan', 'stu02': 'LiSi', 'stu03': 'WangWu', 'stu04': 'ZhaoLiu', 'a': 1, 'b': 2, 'c': 3}
    
    #items  返回字典的(key,value)对元组
    >>> list(stu_info.items())
    [('stu01', 'ZhangSan'), ('stu02', 'LiSi'), ('stu03', 'WangWu'), ('stu04', 'ZhaoLiu'), ('a', 1), ('b', 2), ('c', 3)]
    View Code

    2. 字符串

    和列表、元祖一样,字符串也是一个序列对象,支持索引、切片操作。

    特性:不可修改

    >>> s = 'hello World'
    >>> s.capitalize()        #首字母变大写,其它字母都变小写
    'Hello world'
    >>> s.casefold()        #大写全部变小写
    'hello world'
    >>> s.center(50,"-")
    '-------------------hello World--------------------'
    >>> s.count('l')        #统计"l"出现的次数
    3
    >>> s.encode()        #将字符串编码成bytes格式
    b'hello World'
    >>> s.endswith("ld")        #判断字符串是否以 "ld"结尾
    True
    >>> "hello	world".expandtabs(10)        #将	转换成10个空格
    'hello     world'
    >>> s.find('l')        #查找第一个出现"l"的位置,找到返回其索引, 找不到返回-1 
    2
    
    format:
    >>> msg = "my name is {},and age is {}"
    >>> msg.format("tom",22)
    'my name is tom,and age is 22'
    >>> msg = "my name is {1}, and age is {0}"
    >>> msg.format("tom",22)
    'my name is 22, and age is tom'
    >>> msg = "my name is {name}, and age is {age}"
    >>> msg.format(age=22,name="tom")
    'my name is tom, and age is 22'
    
    format_map:
    >>> msg.format_map({'name':'tom','age':22})
    'my name is tom, and age is 22'
    
    >>> '123'.isdigit()        #检测字符串是否只由数字组成。
    True
    >>> 'asd123'.isalnum()        #检测字符串是否由字母和数字组成。
    True
    >>> u'123'.isnumeric()        #检测字符串是否只由数字组成。这种方法是只针对unicode对象。
    True
    >>> u'23456'.isdecimal()        #检查字符串是否只包含十进制字符。这种方法只存在于unicode对象。
    True
    >>> "      ".isspace()        #检测字符串是否只由空格组成。
    True
    >>> 'Hello World'.istitle()        #检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写。
    True
    >>> 'HELLO WORLD'.isupper()        #检测字符串中所有的字母是否都为大写。
    True
    >>> "-".join(["a","b","c"])        #用于将序列中的元素以指定的字符连接生成一个新的字符串。
    'a-b-c'
    
    maketrans:        #使用maketrans() 方法将所有元音字母转换为指定的数字:
    >>> intab = "aeiou"
    >>> outtab = "12345"
    >>> trantab = str.maketrans(intab, outtab)
    >>>
    >>> str = "this is string example....wow!!!";
    >>> str.translate(trantab)
    'th3s 3s str3ng 2x1mpl2....w4w!!!'
    
    >>> "www.runoob.com".partition(".")        #用来根据指定的分隔符将字符串进行分割。
    ('www', '.', 'runoob.com')
    
    replace:        #把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
    >>> str = "this is string example....wow!!! this is really string";
    >>> str.replace("is", "was")
    'thwas was string example....wow!!! thwas was really string'
    >>> str.replace("is", "was", 3)
    'thwas was string example....wow!!! thwas is really string'
    
    >>> 'Hello World'.swapcase()        #用于对字符串的大小写字母进行转换。
    'hELLO wORLD'
    
    >>> 'hello world'.zfill(20)        #返回指定长度的字符串,原字符串右对齐,前面填充0。
    '000000000hello world'
    
    
    >>> 'hello world'.ljust(20,'-')
    'hello world---------'
    >>> 'hello world'.rjust(20,'-')
    '---------hello world'
    
    
    isidentifier:        #检测一段字符串可否被当作标志符,即是否符合变量命名规则
    >>> str = "ddefdsdff_哈哈"
    >>> str.isidentifier()
    True

     3. 集合

    集合是一个无序的,不重复的数据组合。同样,集合有着广泛的应用,尤其是在涉及数字和数据库的工作中。它的主要作用如下:

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

     限制:

    集合只能包含不可变的(即可散列的)对象类型。因此,列表和字典不能嵌入到集合中,但是,元组是可以嵌入的。

    常用操作

    >>> s = set([2,10,8,3])     #创建一个数值集合
    >>> s
    {8, 3, 2, 10}
    >>> t = set('Hello')     #创建一个唯一字符的集合
    >>> t
    {'e', 'l', 'H', 'o'}
    >>> len(s),len(t)     #查看集合的长度
    (4, 4)
    >>> 3 in s     #测试3是否包含在 s集合 内
    True
    >>> 3 not in s     #测试3是否不包含在 s集合 内
    False
    
    #基本操作
    >>> t.add('world')     #添加一项
    >>> t
    {'l', 'H', 'e', 'world', 'o'}
    >>> s.update([15,26,38])     #在s中添加多项
    >>> s
    {2, 3, 38, 8, 10, 15, 26}
    >>> t.remove('H')     #删除一项
    >>> t
    {'l', 'e', 'world', 'o'}
    >>> len(t)     #集合的长度
    4
    
    >>> s1 = {1,2,3,4}
    >>> s2 = {1,5,3,6}
    >>> s1.intersection(s2)     #交集(返回一个新的 set 包含 s1 和 s2 中的公共元素)
    {1, 3}
    >>> s1 & s2     #同上一个(交集)
    {1, 3}
    >>> s1.union(s2)     #并集(返回一个新的 set 包含 s1 和 s2 中的每一个元素)
    {1, 2, 3, 4, 5, 6}
    >>> s1 | s2     #同上一个(并集)
    {1, 2, 3, 4, 5, 6}
    >>> s1.difference(s2)     #差集(返回一个新的 set 包含 s1 中有但是 s2 中没有的元素)
    {2, 4}
    >>> s1 - s2     #同上一个(差集)
    {2, 4}
    >>> s1.symmetric_difference(s2)     #对称差集(返回一个新的 set 包含 s1 和 s2 中不重复的元素)
    {2, 4, 5, 6}
    >>> s1 ^ s2     #同上一个(对称差集)
    {2, 4, 5, 6}
    
    >>> s1.issubset(s2)     #测试是否 s1 中的每一个元素都在 s2 中
    False
    >>> s1.issubset({1,2,3,4,5,6,7,8})
    True
    >>> s1 <= s2     #同上一个
    False
    >>> s1 <= {1,2,3,4,5,6,7,8}
    True
    >>> s1.issuperset(s2)     #测试是否 s1 中的每一个元素都在 s2 中
    False
    >>> s1.issuperset(set([1,3]))
    True
    >>> s1 >= s2     #同上一个
    False
    >>> s1 >= {1,3}
    True
    
    >>> s1.copy()     #返回集合 s1 的一个浅复制
    {1, 2, 3, 4}
    View Code

    4. 元组

    元组与列表非常类似,也是存一组数,具有列表的大多数属性。但是元组不能在原处修改(它们是不可变的),所以又叫只读列表。

    定义一个元组

    >>> T = ('ZhangSan','LiSi','WangWu','ZhaoLiu','SunQi')

      

    它只有两个方法:

    >>> T.count('WangWu')
    1
    >>> T.index('ZhaoLiu')
    3

     5. 文件

    对文件操作流程:

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

    现有文件如下

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

    基本操作

    >>> f = open(r'd:myfile.txt')     #默认以读模式打开文件
    >>> print(f.readline())     #读取第一行
    Somehow, it seems the love I knew was always the most destructive kind
     
    >>> print(f.readline())     #读取下一行
    不知为何,我经历的爱情总是最具毁灭性的的那种
     
    >>> data = f.read()     #读取剩下的所有内容,文件大时不要用
    >>> print(data)     #打印文件
    Yesterday when I was young
    昨日当我年少轻狂
    The taste of life was sweet
    生命的滋味是甜的
    ......
    ......
    When I was young
    当我年少轻狂
    >>> f.close()     #关闭文件

      

    打开文件的模式有:

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

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

    • r+,可读写文件。【可读;可写;可追加】
    • w+,写读
    • a+,        【可读;不存在则创建;存在则只追加内容;】

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

    • rU
    • r+U

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

    • rb
    • wb
    • ab

    其它语法

    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.
            """
            pass
    View Code

    with语句

    为了避免打开文件后忘记关闭,可以通过管理上下文,即:

    >>> with open(r'd:myfile.txt') as f:
        ...

    如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

    在 Python 2.7后,with又支持同时对多个文件的上下文进行管理,即:

    >>> with open(r'd:myfile1.txt') as obj1,open(r'd:myfile2.txt') as obj2:
        ...
  • 相关阅读:
    菜鸡的Java笔记 第二十八
    菜鸡的Java笔记 第二十七
    菜鸡的Java笔记 第二十六
    菜鸡的Java笔记 第二十五 wrapperClass 包装类
    bzoj3238 [Ahoi2013]差异
    bzoj4516 [Sdoi2016]生成魔咒
    bzoj3998 [TJOI2015]弦论
    bzoj1965 [Ahoi2005]洗牌
    bzoj4896 [Thu Summer Camp2016]补退选
    bzoj5055 膜法师
  • 原文地址:https://www.cnblogs.com/cyfiy/p/7640786.html
Copyright © 2020-2023  润新知