day2 IO文件处理,列表,字典
2015-07-30 13:43
344 查看
一、文件处理
A.file模块
例子:将列表list1中的元素a全部替换成docker
例子:通过文件进行模糊查询
本文出自 “ly36843运维” 博客,请务必保留此出处http://ly36843.blog.51cto.com/3120113/1680065
A.file模块
#已写的模式在当前目录打开一个文件test.txt,会覆盖以前的内容个,如果文件不存在则会自动创建 In [1]: f = file('test.txt','w') #使用file下的方法write往文件里写入内容,此时内容只在内存中,文件中是没有的 In [2]: f.write('Today is a good day\n') In [3]: f.write('this is a test file!') In [4]: f.write('df -h') #将内存中的内容立刻写入到文件中 In [5]: f.flush() #查看文件内容 In [6]: a = file('test.txt','r') In [7]: a.read() Out[7]: 'Today is a good day\nthis is a test file!df -h' #file下的常用方法说明 file('test.txt','r') #表示已只读的方式打开文件,文件必须实现存在 file('test.txt','w') #表示已写的方式打开文件,如果文件不存在,会自动创建文件,如果文件已存在则会覆盖以前的内容 file('test.txt','a') #以追加的方式将内容写入到文件中 f.read() #读取文件内容 f.readline() #一行一行的读取文件 f.close() #关闭后,内容会写入文件 f.tell() #查询指针在文件的什么地方 f.seek(0) #将指针调整到第0个字符的位置,即第一行 f.readline() #依次载入文件所有内容 f.readlines() #把所有的行已列表的形式全部读取出来,会将文件依次全部取出来 f.xreadlines() #一行一行的读取文件到内存空间中,读取文件建议用这个选项例子
[root@python day2]# cat file_handle.py #/usr/bin/env python f = file('/root/fstab') #打开一个文件,默认是以r方式打开的 for line in f.xreadlines(): #从f.xreadlines中一次往内存中读取一行 print line, #逗号是去掉换行符 f.close() #执行结果 [root@python day2]# python file_handle.py # # /etc/fstab # Created by anaconda on Fri Jul 10 09:46:56 2015 # # Accessible filesystems, by reference, are maintained under '/dev/disk' # See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info # UUID=6dfc9d6e-218f-478e-a718-6b6b5b01b7e3 / ext4 defaults 1 1 UUID=b1129597-9bad-46c1-b476-5e9fb2428b56 /boot ext4 defaults 1 2 UUID=efacc2d0-811a-4f9e-b84a-070ec5f93ce1 swap swap defaults 0 0 tmpfs /dev/shm tmpfs defaults 0 0 devpts /dev/pts devpts gid=5,mode=620 0 0 sysfs /sys sysfs defaults 0 0 proc /proc proc defaults 0 0B.fileinput模块
#常用函数 fileinput.input() #返回能够用于for循环遍历的对象 fileinput.filename() #返回当前文件的名称 fileinput.lineno() #返回当前已经读取的行的数量(或者序号) fileinput.filelineno() #返回当前读取的行的行号 fileinput.isfirstline() #检查当前行是否是文件的第一行 fileinput.isstdin() #判断最后一行是否从stdin中读取 fileinput.close() #关闭队列 #选项 files: #文件的路径列表,默认是stdin方式,多文件['1.txt','2.txt',...] inplace: #是否将标准输出的结果写回文件,默认不取代 backup: #备份文件的扩展名,只指定扩展名,如.bak。如果该文件的备份文件已存在,则会自动覆盖。 bufsize: #缓冲区大小,默认为0,如果文件很大,可以修改此参数,一般默认即可 mode: #读写模式,默认为只读 openhook: #该钩子用于控制打开的所有文件,比如说编码方式等;创建测试文件
[root@python day2]# cat test.txt Hello,Python www.linuxeye.com This is a test file利用fileinput实现文件内容替换
#脚本内容二.list操作
[root@python day2]# cat file_input.py
#/usr/bin/env python
import fileinput #导入fileinput模块
for line in fileinput.input('test.txt',backup='_bak',inplace=1):
print line.replace('Python','LinuxEye'), #将字符Python替换为LinuxEye
fileinput.close() #关闭模块
#脚本说明
inplace=1:标准输出会被重定向到打开文件;backup=’_bak’,:替换文件内容之前备份后缀以_bak结尾;另外,在调用fileinput.input()之后记得要fileinput.close()。
#测试
[root@python day2]# cat test.txt Hello,Python www.linuxeye.com This is a test file
[root@python day2]# python file_input.py
[root@python day2]# cat test.txt
Hello,LinuxEye #内容已被替换
www.linuxeye.com
This is a test file
例子:将列表list1中的元素a全部替换成docker
#脚本内容 [root@python day2]# cat lists.py #/usr/bin/env python #元素a,一共有3个 list1 = ['1','a','2','44','a','sdf','a'] print 'The old list1 is: %s' % list1 for i in xrange(list1.count('a')): #写一个循环,次数为元素a的个数 num = list1.index('a') #取出元素a的下标 list1[num] = 'docker' #直接修改指定下标下的元素 print 'The new list1 is: %s ' % list1 #执行结果 [root@python day2]# python lists.py The old list1 is: ['1', 'a', '2', '44', 'a', 'sdf', 'a'] The new list1 is: ['1', 'docker', '2', '44', 'docker', 'sdf', 'docker'] #从结果能看到元素a已经被替换成docker了列表联系程序,写一个购物小程序
[root@python day2]# cat shoplist.py #!/usr/bin/env python import sys products = [['iphone',5500],['MacPro',12000],['NB',680],['cigarate',48],['MX4',2500]] shop_list = [] #make suer salary is convert to a number while True: salary = raw_input('Please input your salary: ').strip() #去除头尾的空白 if not salary.isdigit(): #确保salary能够转换成int类型 continue else: break while True: for p in products: print products.index(p),p[0],p[1] #格式化输出商品信息 choice = raw_input('Please choose sth to buy: ').strip() if choice == 'quit': #如果用户输入的是quit,就退出程序,并打印已购买的商品 print 'you yet buy goods: %s' % shop_list sys.exit('Goodbye!') elif not choice.isdigit() or len(choice) == 0: #输入内容为空或者字符串,就提前进入下一轮循环 print 'you must input an number,not a string and not empty!' continue price = products[int(choice)][1] goods = products[int(choice)][0] if price > int(salary): #商品价格大于工资,提示用户买不起,选择购买其他商品 print 'you not enough money to buy %s,please choose another one!' % goods continue else: salary = int(salary) - price shop_list.append(goods) #将用户购买的商品添加到购物列表中 print 'you yet add %s to your shopping list,you also %s to buy other things!' % (goods,salary) #提示用户已购买的商品,并显示还有多少余额三、字典
例子:通过文件进行模糊查询
[root@python day3]# cat search.py #!/usr/bin/env python import sys staff = {} f = file('stu_info.txt') #打开一个文件 #从文件中一行行的读取内容 for line in f.xreadlines(): stu_id,stu_name,mail,company,title,phone = line.split() #将读取的内容转换成列表 staff[stu_id] = [stu_name,mail,company,title,phone] #使用line.split()[0]做key,line.split()[1:]做value,生成一个列表 while True: query = raw_input('Please input the query string: ').strip() if len(query) == 0: #禁止输入的内容为空 print 'you mount input somthing,not empty!' continue elif query == 'quit': #输入quit就退出脚本 sys.exit('Goodbye!') match_num = 0 #定义一个计数器 #进行模糊查询需要分2步,对key进行匹配和对value进行匹配 for k,v in staff.items(): #对key进行字符串匹配 if k.find(query) != -1: #匹配结果不等于-1表示含有输入的字符串 print k,v #打印字典staff的key和value match_num += 1 else: for i in v: #对字典staff的value进行配置 if i.find(query) != -1: #匹配结果不等于-1表示含有输入的字符串 print k,v #打印staff的key和value match_num += 1 print 'Matched %s records' % match_num #匹配到结果后,打印一共匹配到多少行内容 f.close() #关闭文件
本文出自 “ly36843运维” 博客,请务必保留此出处http://ly36843.blog.51cto.com/3120113/1680065
相关文章推荐
- Android 处理内存泄露的方法
- 常用集合比较
- [转]vi与vim的区别
- tableView的一些基本方法
- VC学习笔记4状态栏
- *Delphi容器类之---Tlist,TStringlist,THashedStringlist的效率比较
- 二叉堆 之 Java的实现
- StringUtil
- android开发之Bundle使用
- android开发之Bundle使用
- 软件概要设计说明书—模板
- 27. JavaScript Cookies
- My Another Blog
- 建立互信
- ACM-字符串-字典树
- android开发之Bundle使用
- java基础知识之初识java之第二章
- [2011noip day2]7.27test解题报告
- strcmp 与 _tcscmp
- android开发之Bundle使用