<--目录-->
1)Python文件处理
2)字符串处理
3)列表、元组、字典的使用
4)集合的妙用
1、文件处理
文件处理模式
r 以只读模式打开文件
w 以只写模式打开文件
a 以追加模式打开文件
r+ 为读写模式 rw跟r+一样,先读后写
w+ 为写读模式,会先清空这个文件,再往里面写
a+ 为追加模式
rb 以读写模式打开
wb 以写读模式打开
ab 以追加及读模式打开
+b 表示必须以二进制的模式处理文件,Windows系统上使用有效,Linux系统上使用无效,但工作中Linux上都加上b为好
f = file(‘test.txt‘) #啥都不写默认表示只读
f.readline() #读一行
f.readlines() #以列表形式读所有行t
f.xreadlines() #不知道文件有多大就用xreadlines
f.read #以字符串形读出来
f.truncate(100) #表示从0开始截取截到100行,不过seek跳到多少行都不影响
f.tell() #查看当前所在文件位置
f.seek(64) #去到第64个位置
f.mode #查看文件打开模式
f.name #查看文件名字
f.close() #关闭文件
f.flush() #刷新
f.write(‘Linux‘) #写内容进文件
f.writelines(‘Linux‘)写入多行
示例:
[root@localhost opt]# cat test.txt hello world what is your name >>> f = file(‘test.txt‘) >>> f.readline() ‘hello world\n‘ >>> f = file(‘test.txt‘) >>> f.readlines() [‘hello world\n‘, ‘what is your name\n‘] >>> f = file(‘test.txt‘) >>> f.read() ‘hello world\nwhat is your name\n‘ >>> f = file(‘test.txt‘) >>> f.tell() 0 >>> f = file(‘test.txt‘) >>> f.seek(10) >>> f.readline() ‘d\n‘ >>> f = file(‘test.txt‘) >>> f.seek(7) >>> f.readline() ‘orld\n‘ >>> f.tell() 12 >>> f.close() >>> f = file(‘test.txt‘) >>> f.mode ‘r‘ >>> f.name ‘test.txt‘ >>> f = file(‘test.txt‘,‘a‘) >>> f.write(‘wsyht‘) >>> f.write(‘\nthird line‘) >>> f.flush() >>> quit()
[root@localhost opt]# cat test.txt hello world what is your name wsyht third line[root@localhost opt]#
追加要关闭f.close()才会写入文件,没关闭就需要刷新f.flush()才会把内容写入文件
>>> f = file(‘test.txt‘) >>> f.encoding >>> print f.encoding None
None代表ASCALL码,Python默认用ASCALL码存,内存用Unicold
综合实战:
strip(‘\n‘) #去掉换行符,strip只会去掉行首和行尾的内容
split(‘:‘) #以冒号为分隔符
示例1:
file文件
[root@localhost opt]# cat file.txt qemu:x:107:107:qemu user:/:/sbin/nologin radvd:x:75:75:radvd user:/:/sbin/nologin wsyht:x:500:500::/home/wsyht:/bin/bash
代码文件
[root@localhost opt]# cat file.py #!/usr/bin/env python f = file(‘file.txt‘,‘rb‘) for line in f.readlines(): #line = line.strip(‘\n‘).split(‘:‘) line = line.strip(‘\n‘) line = line.split(‘:‘) print line print line[0],line[2]
执行过程
[root@localhost opt]# python file.py [‘qemu‘, ‘x‘, ‘107‘, ‘107‘, ‘qemu user‘, ‘/‘, ‘/sbin/nologin‘] qemu 107 [‘radvd‘, ‘x‘, ‘75‘, ‘75‘, ‘radvd user‘, ‘/‘, ‘/sbin/nologin‘] radvd 75 [‘wsyht‘, ‘x‘, ‘500‘, ‘500‘, ‘‘, ‘/home/wsyht‘, ‘/bin/bash‘] wsyht 500
示例2:
f.write(‘Linux‘) #写内容进文件
f.writelines(‘Linux‘)写入多行
[root@localhost opt]# cat file.txt wsyht [root@localhost opt]# cat file.py #!/usr/bin/env python #_*_ coding:utf-8 _*_ f = file(‘file.txt‘,‘ab‘) f.write(‘Linux‘) f.close() [root@localhost opt]# python file.py [root@localhost opt]# cat file.txt wsyht Linux[root@localhost opt]#
>>> a = range(10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a = [str(i) for i in a]
>>> a
[‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘]
f.read 以字节ascall码显示
r+ 先读后写
>>> f = open(‘file.txt‘,‘r+‘)
>>> f.read()
‘qemu:x:107:107:qemu user:/:/sbin/nologin\nradvd:x:75:75:radvd user:/:/sbin/nologin\nwsyht:x:500:500::/home/wsyht:/bin/bash\nline\nline\n‘
2、字符串处理
msg="what is Your Name"
msg.find(‘name‘) #查找字串位置数,报错返回-1
msg.rfind(‘name‘) #反向查找
msg.index(‘name‘) #同find,只是找不到产生ValueError异常
msg.rindex(‘name‘) #同上反向查找
msg.count(‘a‘) #返回字串的个数
msg.capitalize() #首字母大写
msg.lower() #转小写
msg.upper() #转大写
msg.swapcase() #大小写互换
msg.startswith(‘wh‘) #查找以什么开头,真为True,假为Flase
cmp(x,y) #字符串比较,相同大小等于0,第一个大返回1,否则返回-1,
len(msg) #取字符串长度
max(msg) #取字符串最大字符
min(msg) #取字符串最小字符
msg.replace(‘is‘,‘eez‘) #替换字符
b=‘wsyht‘;a=msg+b #拼接字符串
msg=strip(‘\n‘) #去掉换行符,strip只会去掉行首和行尾的内容
msg=split(‘:‘) #将string转list,以冒号切分
msg=split(‘‘) #将string转list,以空格切分
‘_‘.join(msg) #将list转string,以_连接
#示例:
>>> msg="what is Your Name" >>> msg.find(‘name‘) -1 >>> msg.find(‘Name‘) 13 >>> msg.rfind(‘Name‘) 13 >>> msg.index(‘name‘) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found >>> msg.index(‘Name‘) 13 >>> msg.rindex(‘Name‘) 13 >>> msg.count(‘a‘) 2 >>> msg.capitalize() ‘What is your name‘ >>> msg.lower() ‘what is your name‘ >>> msg.upper() ‘WHAT IS YOUR NAME‘ >>> msg.swapcase() ‘WHAT IS yOUR nAME‘ >>> msg="what‘s your wsyht‘s name?" >>> msg "what‘s your wsyht‘s name?" >>> msg += ‘jenkins‘ >>> msg "what‘s your wsyht‘s name?jenkins" >>> msg.split() ["what‘s", ‘your‘, "wsyht‘s", ‘name?jenkins‘] >>> msg.split("‘") [‘what‘, ‘s your wsyht‘, ‘s name?jenkins‘] >>> msg=msg.split("‘") >>> msg [‘what‘, ‘s your wsyht‘, ‘s name?jenkins‘] >>> ‘|‘.join(msg) ‘what|s your wsyht|s name?jenkins‘ >>> ‘__‘.join(msg) ‘what__s your wsyht__s name?jenkins‘ >>> j=‘!!!‘ >>> j.join(msg) ‘what!!!s your wsyht!!!s name?jenkins‘ >>> a = [‘w‘,‘s‘,‘y‘,‘h‘,‘t‘] >>> ‘‘.join(a) ‘wsyht‘ >>> c=‘+‘ >>> c.join(a) ‘w+s+y+h+t‘ >>> b = ‘w‘ >>> b += ‘s‘ >>> b += ‘y‘ >>> b += ‘h‘ >>> b += ‘t‘ >>> b ‘wsyht‘ >>> dirs=‘‘,‘usr‘,‘bin‘,‘env‘ >>> dirs (‘‘, ‘usr‘, ‘bin‘, ‘env‘) >>> ‘/‘.join(dirs) ‘/usr/bin/env‘ >>> print ‘c:‘ + ‘\\‘.join(dirs) c:\usr\bin\env >>> x=‘Abc‘ >>> x ‘Abc‘ >>> x.startswith(‘Ac‘) False >>> x.startswith(‘Ab‘) True >>> i=[1,3,5] >>> i [1, 3, 5] >>> len(i) 3 >>> max(i) 5 >>> min(i) 1 >>> x = ‘A‘ >>> y = ‘C‘ >>> a = ‘5‘ >>> b = ‘2‘ >>> cmp(x,y) -1 >>> cmp(a,b) 1 >>> cmp(10,10) 0 >>> msg="what is Your Name" >>> msg.replace(‘is‘,‘eez‘) ‘what eez Your Name‘ >>> b=‘wsyht‘ >>> msg + b ‘what is Your Namewsyht‘
3、列表、元组、字典
#列表
name_list = [‘wsyht‘,‘jack‘,‘jenkins‘]
name_list.oppend(‘test‘) #追加元素
name_list.insert(2,168) #插入元素到指定位置
name_list.remove(‘wsyht‘) #删除第一次出现的该元素
name_list.count(‘wsyht‘) #该元素在列表中出现的个数
name_list.index(‘wsyht‘) #该元素的位置,无则抛异常
name_list.sort #排序
name_list.reverse #倒序
name_list.pop #返回最后一个元素,并从list中删除之
name_list.extend(list) #追加list,即合并到list到name_list上
name_liset[1:] #片段操作符,用于子list的提取,分片
[1+2]+[3+4] #为[1,2,3,4],同extend()
[2]*4 #为[2,2,2,2]
del name_list[1] #删除指定下标的元素
del name_list[1:3] #删除指定下标范围的元素
name=name_list #name为name_list的别名,用c来说就是指针相同,对name的操作即对name_list的操作
name_list[1::2] #隔一个取一个
name_list[1::3] #隔两个取一个
range(name_list.count(‘wsyht‘)) #取得这个重复数的第一位到最后一位数值
#示例
>>> name_list = [‘wsyht‘,‘jack‘,‘jenkins‘] >>> name_list[2] ‘jenkins‘ >>> name_list[0] ‘wsyht‘ >>> name_list.append(‘docker‘) >>> name_list [‘wsyht‘, ‘jack‘, ‘jenkins‘, ‘docker‘] >>> name_list.insert(2,168) >>> name_list [‘wsyht‘, ‘jack‘, 168, ‘jenkins‘, ‘docker‘] >>> name_list.remove(‘docker‘) >>> name_list [‘wsyht‘, ‘jack‘, 168, ‘jenkins‘] >>> name_list.append(‘wsyht‘) >>> name_list [‘wsyht‘, ‘jack‘, 168, ‘jenkins‘, ‘wsyht‘] >>> name_list.count(‘wsyht‘) 2 >>> name_list.index(‘wsyht‘) 0 >>> name_list [‘wsyht‘, ‘jack‘, 168, ‘jenkins‘, ‘wsyht‘] >>> del name_list[2] >>> name_list [‘wsyht‘, ‘jack‘, ‘jenkins‘, ‘wsyht‘] >>> name_list [‘jack‘, ‘jenkins‘, ‘wsyht‘, ‘wsyht‘] >>> name_list.reverse() >>> name_list [‘wsyht‘, ‘wsyht‘, ‘jenkins‘, ‘jack‘] >>> name_list.pop() ‘jack‘ >>> name_list [‘wsyht‘, ‘wsyht‘, ‘jenkins‘] >>> name_list.pop() ‘jenkins‘ >>> name_list [‘wsyht‘, ‘wsyht‘] >>> name_list=[‘Eric‘,‘wsyht‘,‘jack‘,‘tom‘] >>> name_list.append(‘!‘) >>> name_list.append(‘#‘) >>> name_list.append(‘*‘) >>> name_list [‘Eric‘, ‘wsyht‘, ‘jack‘, ‘tom‘, ‘!‘, ‘#‘, ‘*‘] >>> ord(‘#‘) 35 #查看ascall码特殊符号数字大小 >>> ord(‘!‘) 33 >>> ord(‘*‘) 42 >>> name_list.sort() #按ascall码数字由小到大进行排序 >>> name_list [‘!‘, ‘#‘, ‘*‘, ‘Eric‘, ‘jack‘, ‘tom‘, ‘wsyht‘] >>> help(name_list.sort) infos=[1,2,3,4,5,6] >>> infos = [1,2,3,4,5,6] >>> name_list,infos ([‘!‘, ‘#‘, ‘*‘, ‘Eric‘, ‘jack‘, ‘tom‘, ‘wsyht‘], [1, 2, 3, 4, 5, 6]) >>> name_list.extend(infos) >>> name_list [‘!‘, ‘#‘, ‘*‘, ‘Eric‘, ‘jack‘, ‘tom‘, ‘wsyht‘, 1, 2, 3, 4, 5, 6] >>> name_list += infos >>> name_list [‘!‘, ‘#‘, ‘*‘, ‘Eric‘, ‘jack‘, ‘tom‘, ‘wsyht‘, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6] >>> name_list[2:5] [‘*‘, ‘Eric‘, ‘jack‘] >>> name_list[2:5] [‘*‘, ‘Eric‘, ‘jack‘] >>> name_list[-5] 2 >>> name_list[-5:-1] [2, 3, 4, 5] >>> name_list[-5:-0] [] >>> name_list[0:5] [‘!‘, ‘#‘, ‘*‘, ‘Eric‘, ‘jack‘] >>> name_list[:5] [‘!‘, ‘#‘, ‘*‘, ‘Eric‘, ‘jack‘] >>> name_list=[‘!‘, ‘#‘, ‘*‘, ‘Eric‘, ‘jack‘, ‘tom‘, ‘wsyht‘, 1, 4, 5, 6, 1, 2, 3, 4, 5, 6] >>> del name_list[5:11] >>> name_list [‘!‘, ‘#‘, ‘*‘, ‘Eric‘, ‘jack‘, 1, 2, 3, 4, 5, 6] >>> name_list[1:] [‘#‘, ‘*‘, ‘Eric‘, ‘jack‘, 1, 2, 3, 4, 5, 6] >>> a=[1,2,3] >>> b=[‘a‘,‘b‘,‘c‘] >>> a+b [1, 2, 3, ‘a‘, ‘b‘, ‘c‘] >>> a [1, 2, 3] >>> b [‘a‘, ‘b‘, ‘c‘] >>> c=a+b >>> c [1, 2, 3, ‘a‘, ‘b‘, ‘c‘] >>> [2]*4 [2, 2, 2, 2] >>> b=[2]*4 >>> b [2, 2, 2, 2] >>> name_list [‘!‘, ‘#‘, ‘*‘, ‘Eric‘, ‘jack‘, 1, 2, 3, 4, 5, 6] >>> name_list[1::2] [‘#‘, ‘Eric‘, 1, 3, 5] >>> name_list[1::3] [‘#‘, ‘jack‘, 3, 6] >>> a = range(10) >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> a[::2] [0, 2, 4, 6, 8] >>> a[1::2] [1, 3, 5, 7, 9] >>> a[1::3] [1, 4, 7] >>> name_list [‘!‘, ‘#‘, ‘*‘, ‘Eric‘, ‘jack‘, 1, 2, 3, 4, 5, 6, 2] >>> name_list.count(2) 2 >>> range(name_list.count(2)) [0, 1]
#元组
tuple:元组 (即常量数组)
tuple=(‘a‘,‘b‘,‘c‘,‘d‘,‘e‘)
可以用list的[],:操作符提取过素。就是不能直接修改元素
#示例
>>> a = (1,2,3,4) >>> a (1, 2, 3, 4) >>> list(a) [1, 2, 3, 4] >>> a (1, 2, 3, 4) >>> a=list(a) >>> a [1, 2, 3, 4] >>> type(a) <type ‘list‘> >>> tuple(a) (1, 2, 3, 4) >>> a [1, 2, 3, 4] >>> a=tuple(a) >>> a (1, 2, 3, 4) >>> type(a) <type ‘tuple‘>
【字典】
name_info.poitem #得到第一个字典,删除第一个字典元素
name_info.pop(‘job‘) #删除指定的元素
#脚本示例1:
[root@localhost opt]# cat dict.py #!/usr/bin/env python name_info = { ‘name‘: ‘wsyht‘, ‘age‘: 29, ‘job‘: ‘yunwei‘ } print name_info[‘name‘] print name_info[‘age‘] print name_info[‘job‘]
#终端实践
>>> name_info = { ... ‘name‘: ‘wsyht‘, ... ‘age‘: 29, ... ‘job‘: ‘yunwei‘ ... } >>> name_info {‘job‘: ‘yunwei‘, ‘age‘: 29, ‘name‘: ‘wsyht‘} >>> >>> >>> name_info[‘wsyht‘]=3000 >>> name_info {‘job‘: ‘yunwei‘, ‘age‘: 29, ‘wsyht‘: 3000, ‘name‘: ‘wsyht‘} >>> name_info[‘job‘]=‘IT‘ >>> name_info {‘job‘: ‘IT‘, ‘age‘: 29, ‘wsyht‘: 3000, ‘name‘: ‘wsyht‘} >>> name_info.pop(‘job‘) ‘IT‘ >>> name_info {‘age‘: 29, ‘wsyht‘: 3000, ‘name‘: ‘wsyht‘} >>> name_info.popitem() (‘age‘, 29) >>> name_info {‘wsyht‘: 3000, ‘name‘: ‘wsyht‘}
#脚本示例2:
[root@localhost opt]# cat dict.py #!/usr/bin/env python name_info = { ‘name‘: ‘wsyht‘, ‘age‘: 29, ‘job‘: ‘yunwei‘, ‘slalary‘: 333, ‘address‘: ‘BJ‘, ‘qender‘: ‘Male‘ } for i in name_info: print i, name_info[i]
#脚本执行
[root@localhost opt]# python dict.py name wsyht age 29 slalary 333 job yunwei address BJ qender Male
未完待续。。。
本文出自 “wsyht的博客” 博客,请务必保留此出处http://wsyht2015.blog.51cto.com/9014030/1795761
Python笔记第2章,文件,字符串,列表,元组,字典,集合的使用
原文地址:http://wsyht2015.blog.51cto.com/9014030/1795761