Python文件处理
文件内容替换
for line infileinput.input(“filepath”,inplace=1):
line=line.replace(“oldtest”,”newtest”)
print line,
//包含oldtest的替换成newtest
例子:
wangchao@wangchao-virtual-machine:~/python$vim finput.py
#!/usr/bin/env python
import fileinput
for line infileinput.input("contact_list.txt",backup=‘bak‘,inplace=1):
line = line.replace(‘wang‘,‘chao‘)
print line,
//将文件中wang改成chao,并将原文件备份一份bak文件
程序运行结果
wangchao@wangchao-virtual-machine:~/python$python finput.py
wangchao@wangchao-virtual-machine:~/python$ls
contact_list.txtbak
修改某行
with open(“foo.txt”,”r+”) as f:
old=f.read()#read everything in the file
f.seek()#rewind
f.write(“new line\n”+old)#write the new
line before
例子:
wangchao@wangchao-virtual-machine:~/python$vim fseek.py
#f = open(‘contact_list.txt‘,‘r+‘)
withopen(‘contact_list.txt‘,"r+") as f :
old = f.read()
f.seek(14)
f.write("new line\n")
//f.seek(14),文件从第14个字符开始加newline,并换行
程序运行结果
wangchao@wangchao-virtual-machine:~/python$more contact_list.txt
1 cai chengxnew 1885
2 ru gongchengshi 1886
3 chao gongchengshi 1887
4 yao chengxuyuan 1888
wangchao@wangchao-virtual-machine:~/python$python fseek.py
wangchao@wangchao-virtual-machine:~/python$more contact_list.txt
1 cai chengxnew line
85
2 ru gongchengshi 1886
3 chao gongchengshi 1887
4 yao chengxuyuan 1888
wangchao@wangchao-virtual-machine:~$ vimtest.txt
wangchao@wangchao-virtual-machine:~/python$python
>>> f=file(‘test.txt‘) //打开只读模式
>>> f=file(‘test.txt‘,‘w‘) //打开可写
>>> f.write(‘hello world!‘) //写入
>>> f.flush() //文件新建或被保存
>>> f.close()
>>> f=file(‘test.txt‘,‘a‘)
>>> f.write(‘AAA‘) //追加内存
wangchao@wangchao-virtual-machine:~/python$cat test.txt
hello world!AAA
python列表
处理和存放一组数据
用途:购物列表、工资列表……
语法:ShoppingList =[‘car’,’clothes’,’iphone’]
添加book到ShoppingList列表:shoppingList.append(‘book’)
删除car: ShoppingList.remove(‘car’)
删除最后一个: ShoppingList.pop()
删除列表中第二个内容:ShoppingList.pop(1)
wangchao@wangchao-virtual-machine:~/python$python
>>>nameList=[‘wang‘,‘cai‘,‘ru‘,‘yao‘]
>>> nameList
[‘wang‘, ‘cai‘, ‘ru‘, ‘yao‘]
>>> nameList[2] //取出2号,从0开始数
‘ru‘
>>> nameList[-1] //取出最后一个
‘yao‘
>>> nameList.append(‘fei‘) //加入fei
>>> nameList
[‘wang‘, ‘cai‘, ‘ru‘, ‘yao‘, ‘fei‘]
>>> nameList.insert(2,‘sun‘) //在2号前插入sun
>>> nameList
[‘wang‘, ‘cai‘, ‘sun‘, ‘ru‘, ‘yao‘, ‘fei‘]
>>> nameList.count(‘wang‘) //统计wang出现的个数
1
>>> ‘cai‘ in nameList //判断cai是否在列表中
True
>>> nameList
[‘wang‘, ‘cai‘, ‘sun‘, ‘ru‘, ‘yao‘, ‘fei‘]
>>> nameList.index(‘fei‘) //索引,fei在列表中的位置
5
>>> nameList.pop() //删除最后一个
‘fei‘
>>> nameList
[‘wang‘, ‘cai‘, ‘sun‘, ‘ru‘, ‘yao‘]
>>> nameList.remove(‘Y‘) //删除一个元素Y,如果其中有两个Y,将只删除前面一个
>>> nameList.reverse() //排序
>>> nameList
[‘yao‘, ‘ru‘, ‘sun‘, ‘cai‘, ‘wang‘]
>>> nameList.reverse() //排回
>>> nameList
[‘wang‘, ‘cai‘, ‘sun‘, ‘ru‘, ‘yao‘]
>>> nameList.sort() //按字母排序
>>> nameList
[‘cai‘, ‘ru‘, ‘sun‘, ‘wang‘, ‘yao‘]
>>> nameList.extend(‘hello world‘)
>>> nameList
[‘cai‘, ‘ru‘, ‘sun‘, ‘wang‘, ‘yao‘, ‘h‘,‘e‘, ‘l‘, ‘l‘, ‘o‘, ‘ ‘, ‘w‘, ‘o‘, ‘r‘, ‘l‘, ‘d‘]
>>> nameList[1]=‘ruru‘ //修改1号为ruru
>>> nameList
[‘cai‘, ‘ruru‘, ‘sun‘, ‘wang‘, ‘yao‘, ‘h‘,‘e‘, ‘l‘, ‘l‘, ‘o‘, ‘ ‘, ‘w‘, ‘o‘, ‘r‘, ‘l‘, ‘d‘]
>>> nameList.index(‘h‘) //查找h所在的位置
5
>>> i=nameList.index(‘h‘)
>>> nameList[i]=‘H‘ //将h改成H
>>> nameList
[‘cai‘, ‘ruru‘, ‘sun‘, ‘wang‘, ‘yao‘, ‘H‘,‘e‘, ‘l‘, ‘l‘, ‘o‘, ‘ ‘, ‘w‘, ‘o‘, ‘r‘, ‘l‘, ‘d‘]
元组
与列表一样,但内容一旦生成,不可修改
NameList=(‘cai’,’ru’,’wang’)
遍历列表
NameList=[‘cai’,’ru’,’wang’]
for name in NameList
Print‘your name is’,name
列表练习程序
让用户输入工资
输出购物菜单及产品价格
计算用户是否可支付
输出用户剩余的钱,问用户是否可继续购物,如果选择继续,继续进行,直到钱不够为止
补充:
>>> names="cai ru wang" //定义一变量为字符串
>>> names.split() //将字符串分成一个列表
[‘cai‘, ‘ru‘, ‘wang‘]
>>> name_list=names.split()
>>> name_list //字符串被分成三段
[‘cai‘, ‘ru‘, ‘wang‘]
>>> name_list[1] //取出ru
‘ru‘
F_choice=choice.strip() //使choice脱去空格(多余的)
参考程序:
wangchao@wangchao-virtual-machine:~/python$vim mai.py
#!/usr/bin/python
import tab
import sys
products = [‘Car‘,‘Iphone‘,‘Coffee‘,‘Mac‘,‘Cloths‘,‘Bicyle‘]
prices = [250000,4999, 35, 9688, 438, 1500]
shop_list=[]
salary = int(raw_input(‘please input yoursalary:‘))
while True:
print "Things have in the shop.plesae choose one to buy:"
for p in products:
print p,‘\t‘,prices[products.index(p)]
choice = raw_input(‘Please input one item to buy:‘)
F_choice = choice.strip()
if F_choice in products:
product_price_index = products.index(F_choice)
product_price = prices[product_price_index]
print F_choice,product_price
if salary > product_price:
shop_list.append(F_choice)
print "Added %s intoyour shop list" % F_choice
salary = salary -product_price
print "Salaryleft:",salary
else:
if salary < min(prices):
print ‘Sorry,rest ofyour salary cannot buy anything! 88‘
print "you havebought these things: %s" % shop_list
sys.exit()
else:
print "Sorry ,youcannot afford this product,please try other ones!"
程序运行结果:
wangchao@wangchao-virtual-machine:~/python$python mai.py
please input your salary:1536
Things have in the shop.plesae choose oneto buy:
Car 250000
Iphone 4999
Coffee 35
Mac 9688
Cloths 438
Bicyle 1500
Please input one item to buy:Car
Car 250000
Sorry ,you cannot afford thisproduct,please try other ones!
Things have in the shop.plesae choose oneto buy:
Car 250000
Iphone 4999
Coffee 35
Mac 9688
Cloths 438
Bicyle 1500
Please input one item to buy:Bicyle
Bicyle 1500
Added Bicyle into your shop list
Salary left: 36
Things have in the shop.plesae choose oneto buy:
Car 250000
Iphone 4999
Coffee 35
Mac 9688
Cloths 438
Bicyle 1500
Please input one item to buy:Bicyle
Bicyle 1500
Sorry ,you cannot afford thisproduct,please try other ones!
Things have in the shop.plesae choose oneto buy:
Car 250000
Iphone 4999
Coffee 35
Mac 9688
Cloths 438
Bicyle 1500
Please input one item to buy:Coffee
Coffee 35
Added Coffee into your shop list
Salary left: 1
Things have in the shop.plesae choose oneto buy:
Car 250000
Iphone 4999
Coffee 35
Mac 9688
Cloths 438
Bicyle 1500
Please input one item to buy:Coffee
Coffee 35
Sorry,rest of your salary cannot buyanything! 88
you have bought these things: [‘Bicyle‘,‘Coffee‘]
wangchao@wangchao-virtual-machine:~/python$
Python字典讲解与练习
python字典
语法:
DicName={
“key1”: “value”,
“key2”: “value 2”
Contacs={
‘wang’: ‘1886’,
‘cai’: ‘1887’,
‘ru’: ‘1888’,
}
将之前写的购物菜单用字典写:
>>> product_dir={‘car‘:250000,‘Iphone‘:4999,‘coffee‘:35,‘Bicycle‘:1500}
>>> product_dir //查看菜单
{‘car‘: 250000, ‘coffee‘: 35, ‘Bicycle‘:1500, ‘Iphone‘: 4999}
>>> product_dir[‘coffee‘] //查价格
35
>>> product_dir.keys() //查key
[‘car‘, ‘coffee‘, ‘Bicycle‘, ‘Iphone‘]
>>> product_dir.values() //查values
[250000, 35, 1500, 4999]
>>> product_dir.items() //查相对应的
[(‘car‘, 250000), (‘coffee‘, 35),(‘Bicycle‘, 1500), (‘Iphone‘, 4999)]
>>> for i in product_dir: //打印product_dir
... print i
...
car
coffee
Bicycle
Iphone
>>> product_dir.items()
[(‘car‘, 250000), (‘coffee‘, 35),(‘Bicycle‘, 1500), (‘Iphone‘, 4999)]
>>> for p,price in product_dir.items(): //打印items()
... print p,price
...
car 250000
coffee 35
Bicycle 1500
Iphone 4999
字典查看、添加、删除、修改
语法:
Contacs={
‘wang’:’1886’,
‘cai’:’1887’;
‘ru’:’1888’}
查看key: Contacts.key()
查看value: Contacts.values()
添加新item到字典: Contacts[‘yao’]=’1889’
删除item: Contacts.popitem() //默认删除第一个
>>> product_dir
{‘car‘: 250000, ‘coffee‘: 35, ‘Bicycle‘:1500, ‘Iphone‘: 4999}
>>>product_dir.has_key(‘car‘) //判断car是否存在
True
>>> product_dir.popitem() //删除第一个
(‘car‘, 250000)
>>> product_dir
{‘coffee‘: 35, ‘Bicycle‘: 1500, ‘Iphone‘:4999}
练习小程序:员工信息表
1.创建公司员工信息表,员工号、姓名、职位、手机
2.提供查找接口,通过员工姓名查询用户信息
参考程序:
wangchao@wangchao-virtual-machine:~/python$cat contact_list.txt
1 cai chengxuyuan 1885
2 ru gongchengshi 1886
3 chao gongchengshi 1887
4 yao chengxuyuan 1888
wangchao@wangchao-virtual-machine:~/python$vim contact_dir.py
#!/usr/bin/python
import tab
contact_file = ‘contact_list.txt‘
f = file(contact_file)
contact_dic = {}
for line in f.readlines():
name = line.split()[1]
contact_dic[name] = line
‘‘‘
for n,v in contact_dic.items():
print "%s \t%s" %(n,v),
‘‘‘
while True:
input = raw_input("Please input the staff name:").strip()
if len(input) == 0:continue
if contact_dic.has_key(input):
print "\033[32.1m%s\033[0m" % contact_dic[input]
else:
print ‘Sorry,no staff namefound!‘
程序运行结果:
wangchao@wangchao-virtual-machine:~/python$python contact_dir.py
Please input the staff name:zhou
Sorry,no staff name found!
Please input the staff name:cai
1 cai chengxuyuan 1885
Please input the staff name:chao
3 chao gongchengshi 1887
Please input the staff name:yao
4 yao chengxuyuan 1888
Please input the staff name:ru
2 ru gongchengshi 1886
Please input the staff name:
Python函数
函数是在程序中将一组用特定的格式包装起,定义一个名称,然后可以在程序的任何地方通过调用此函数名来执行函数里的那组命令
使用函数的好处:
程序可扩展性
减少程序代码
方便程序架构的更改
定义函数
def sayHi():
print“hello,world!”
def sayHi2(name):
print“hello,%s,howare you?” %name
n=’wang’
sayHi2(n)
>>>sayHi(n)
Hello,wang,how are you?
小试牛刀1:
wangchao@wangchao-virtual-machine:~/python$vim function1.py
#!/usr/bin/env python
def sayHi(n):
print "Hello %s,how are you?" % n
name = ‘wang‘
sayHi(name)
wangchao@wangchao-virtual-machine:~/python$python function1.py
Hello wang,how are you?
小试牛刀2:
wangchao@wangchao-virtual-machine:~/python$more contact_list.txt
1 cai chengxuyuan 1885
2 ru gongchengshi 1886
3 chao gongchengshi 1887
4 yao chengxuyuan 1888
将名字取出,一个一个问hello XXX,how are you
参考:
wangchao@wangchao-virtual-machine:~/python$vim function2.py
#!/usr/bin/python
def sayHi(n):
print "hello %s,how are you?" %n
contact_file =‘contact_list.txt‘
f = file(contact_file)
for line in f.readlines():
name = line.split()[1]
sayHi(name)
程序结果:
wangchao@wangchao-virtual-machine:~/python$python function2.py
hello cai,how are you?
hello ru,how are you?
hello chao,how are you?
hello yao,how are you?
函数参数
def info(name,age):
print“Name:%s Age:%s” %(name,age)
综合练习:
写一个atm程序,功能要求:
额度15000
可以提现,手续费5%
每月最后一天出账单(每月30天)
记录每月日常消费流水
提供还款接口
优化(可选):
1.每月10号为还款日,过期未还,按欠款额5%计息
输出类似:
本期还款总额: XX
交易日 交易摘要 交易金额 计息
XX XX XX XX
补充:Pickle()#、函数默认参数、关键参数可学习一下,写程序可更加便捷
本文出自 “Linux学习笔记” 博客,请务必保留此出处http://9656134.blog.51cto.com/9646134/1685437
原文地址:http://9656134.blog.51cto.com/9646134/1685437