Python 运维开发 学习记录 语言基础(二)

Shell/Python   字典和列表   文件处理  

一、模块的原理

  • from os import system,popen
  • from os import * 不推荐
  • import commands
  • __init__.py

二、文件处理

  • read 读 r
f = file("py_home_work.csv","r")  
for line in f.readlines():  
    print line,
f.close()  
  • write 写 w
f = file("test.txt","w")  
f.write("This is the first line\n")  
f.write("This is the second line\n")  
f.write("This is the third line\n")  
f.close()  
  • append 追加 a
f = file("test.txt","a")  
f.write("This is the appending part,i am different\n")  
f.write("This is the appending part,i am different\n")  
f.close()  
  • 修改
#read and write : r+ w+

f = file("test.txt","r+")  
print 'first line:',f.readline()  
print 'second line:',f.readline()  
f.write("change third line")  
print 'third:',f.readline()

f.close()  
  • f.tell 返回一个整数,表示当前文件指针的位置
  • f.seek 用来移动文件指针
  • 另一种打开方式
with open("test.txt","r") as f:  
   f.seek(0)
   data = f.readlines()

三、自动更改文件内容

  • 将指定的字符串,替换成新的字符串 [此方法只能替换相同长度的字符串]
#!/usr/bin/python
import sys  
if len(sys.argv) < 2:  
        print len(sys.argv)
        print "exit"

if '-r' in sys.argv:  
        rep_argv_pos = sys.argv.index('-r')
        find_str = sys.argv[rep_argv_pos + 1]   #原字符串
        new_str = sys.argv[rep_argv_pos + 2]    #新字符串
else:  
        print "argv is not exist"
        exit()

f = file('passwd','r+')  
while True:  
        line = f.readline()         
        if find_str in line:
                #指定字符串起始位置 = 当前位置 - 当前行的字符长度
                last_line_pos = f.tell() - len(line)
                #跳到指定字符串的前一行最后的位置
                f.seek(last_line_pos)
                # 将指定字符串修改为新字符串
                new_line = line.replace(find_str,new_str)
                print new_line
                f.write(new_line)
                break
f.close()  
  • 使用fileinput模块修改
# inplace = 1 时修改才会写到文件里,默认等于0时只会在内存里修改
>>> import fileinput
>>> for line in fileinput.input("passwd",inplace=1):
...    print line.replace("man","MAN")

# 修改原文件并,并把原文件备份一个.bak结尾的文件
>>> for line in fileinput.input("passwd",inplace=1,backup='.bak'): 
...     print line.replace("MAN","leoiceo")

四、字符编码

  • ASCII Unicode Utf-8
  • 字符编解码的故事
  • 编写python代码前在开头加上#_*_coding:utf-8_*_
  • Unicode 在中文字符前加上小u
    print u'你好,世界'

五、列表

  • list的方法
L.append(var)       #追加元素  
L.insert(index,var)  
L.pop(var)          #返回最后一个元素,并从list中删除之  
L.remove(var)       #删除第一次出现的该元素  
L.count(var)        #该元素在列表中出现的个数  
L.index(var)        #该元素的位置,无则抛异常  
L.extend(list)      #追加list,即合并list到L上  
L.sort()            #排序  
L.reverse()         #倒序  

a[1:]               #片段操作符,用于子list的提取  
[1,2]+[3,4]         #为[1,2,3,4]。同extend()      
[2]*4               #为[2,2,2,2]  
del L[1]            #删除指定下标的元素  
del L[1:3]          #删除指定下标范围的元素  
  • list的复制  
L1 = L              #L1为L的别名,用C来说就是指针地址相同,对L1操作即对L操作  
L1 = L[:]           #生成L的一个COPY  
  • 购物车小练习
  • 初版
products = ["apple","bike","Telas","Coffee"]  
prices = [ 3000,1900,80000,35 ]

print "==========Welcome to leoiceo pyshop!========="  
mymoney = int(raw_input("Please input your money: "))  
buy_list = []

while True:

    for p in products:
        pindex = products.index(p)
        print
        print pindex,p,prices[pindex]

    buy_pro = int(raw_input("Please input you want buy product: "))
    if products[buy_pro] in products and mymoney > int(prices[buy_pro]) :
        mymoney = mymoney - int(prices[buy_pro])
        buy_list.append(products[buy_pro])
        print "--->buy %s,you money only %s" % (products[buy_pro],mymoney)
    else:
        print "You Not enough money,only money: %s" % mymoney
        for bl in buy_list:
            print "You buy product list: %s\n" % bl
        break
  • 优化版
__author__ = 'leoiceo'  
#_*_coding:utf-8_*_

products = [  
    ['Apple',5000],
    ['Ipad',3500],
    ['Tesla',800000],
    ['Coffee',35],
    ['Clothes',500],
    ['Shoses',800],
]

salary = 9000  
shop_list = []  
while True:  
    print 'Please choise your want buy:'
    for index,p in enumerate(products):
        print ''' %s  %s price %s''' % (index,p[0],p[1])
    choise = raw_input("Choose sth to buy: ").strip()
    if choise.isdigit():
        choise = int(choise)
        p_price =  products[choise][1]
        if p_price < salary:
            shop_list.append(products[choise])
            salary -= p_price
            print "Has added \033[31;1m%s\033[0m into shop list,your current balance is \033[31;1m%s\033[0m" \
            % (products[choise][0],salary)
        else:
            print "\033[41;1mMony is not enough,try thing else jera!\033[0m"

    elif choise == 'quit':
        print "-----shopping list --------"
        for k,v in enumerate(shop_list):
            print k,v
        print "Your current balance is \033[31;1m%s\033[0m" % salary
        print "-------------bye-------------"
        break

六、字典

  • 方法
D.get(key, 0)       #同dict[key],多了个没有则返回缺省值,0。[]没有则抛异常  
D.has_key(key)      #有该键返回TRUE,否则FALSE  
D.keys()            #返回字典键的列表  
D.values()          #以列表的形式返回字典中的值,返回值的列表中可包含重复元素  
D.items()           #将所有的字典项以列表方式返回,这些列表中的每一项都来自于(键,值),但是项在返回时并没有特殊的顺序  
  
D.update(dict2)     #增加合并字典  
D.popitem()         #得到一个pair,并从字典中删除它。已空则抛异常  
D.clear()           #清空字典,同del dict  
D.copy()            #拷贝字典  
D.cmp(dict1,dict2)  #比较字典,(优先级为元素个数、键大小、键值大小)  
                    #第一个大返回1,小返回-1,一样返回0
            
dictionary的复制  
dict1 = dict        #别名  
dict2=dict.copy()   #克隆,即另一个拷贝。  
  • 列表VS字典

    • dict:
      查找和插入的速度极快,不会随着key的增加而增加 需要占用大量的内存,内存浪费多。 KEY不可变
      默认无序
    • list
      查找和插入的时间随着元素的增加而增加 占用空间小,浪费内存很少 通过下标查询 有序
  • 用字典做多级菜单

menu = {  
    "Beijing" :{
        "Chaoyang":{
            "CBD":["CCIC","CCTV"],
            "WangJing":["Momo","ChuiZi"]
        },
         "HaiDian": ["Baidu","YouKu"]
    },
    "Shanghai":{
        "PuDong":["Ctrip","1 shop"],
        "PuXi":["China Bank","America Bank"]
    }
}

exit_flag = False

while not exit_flag:  
    for index,key in enumerate(menu.keys()):
        print index,key
    choise_1 = raw_input("please choise your like city: ")
    if choise_1.isdigit():
        choise_1 = int(choise_1)
        key_1 = menu.keys()[choise_1]
        print key_1
        while not exit_flag:
            for index,key in enumerate(menu[key_1]):
                print '--->',index,key
            choise_2 = raw_input("Please choise your like area: ")
            if choise_2.isdigit():
                choise_2 = int(choise_2)
                key_2 =  menu[key_1].keys()[choise_2]
                #print key_2
                while not exit_flag:
                    for index,key in enumerate(menu[key_1][key_2]):
                        print '-->-->',index,key
                    choise_3 = raw_input("Please choise your like company: ")
                    if choise_3.isdigit():
                        print "This is the last level....."
                    elif choise_3 == "quit":
                        exit_flag = True
                    elif choise_3 == "back":
                        break
                else:
                    print "-----going to quit-----"