Python运维基础(1)列表元祖字典文件

  • 用Python做什么
    • 软件开发
      • 游戏,搜索,嵌入式…
      • 网站
      • C\S软件
    • 系统管理
      • 脚本
      • 运维自动化工具

编程风格

  • 语法要求
    • 缩进统一
  • 变量
    • 标识符的第一个字符必须是字母表中的字母(大写或小写)或者一个下划线(‘_’)

Error:
a = ‘Hello, everybody. I’m Alex’
有三个引号,不能识别,正确写法如下:
a = “Hello, everybody. I’m Alex”

用户交互
python 3.x下使用内建函数input()
python 2.x下使用内建函数raw_input()

eg:
name = input(‘name’)
print(name)


流程控制

-条件: if..elif..else

name = input('Name:')
age = int(input('Age:'))
job = input('Job:')
print('%s\n%d\n%s\n' % (name, age, job))
if age < 18:
    print('child~')
elif age == 20:
    print('great~')
else:
    print('adult~')

-循环: for,while

for循环

for i in range(1, 100):
    print('The number is %d' % i)
    if i == 13:
        print("Love you ~ You get Taylor Swift's lucky number!")

while循环

i = 1
while True:
    username = input('Please input your username:')
    if username == 'zhuzhuzhu':
        password = input('Please input your password:')
        p = '831143'
        while password != p:
            password = input('Wrong password !Try again:')
            i += 1
            if i >= 3:
                break
        else:
            print('Welcome login to  TriAquae!')
            break

    else:
        print('Sorry, user %s is not found' % username)

练习程序 1

编写可供用查询的学生信息表!
用户认证
ID Name Class QQ
查询关键字:姓名

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: zhuzhuzhu   time:2017/11/17
"""
name = input('Name:')
age = int(input('Age:'))
job = input('Job:')
print('%s\n%d\n%s\n' % (name, age, job))
if age < 18:
    print('child~')
elif age == 20:
    print('great~')
else:
    print('adult~')
"""

"""
for i in range(1, 100):
    print('The number is %d' % i)
    if i == 13:
        print("Love you ~ You get Taylor Swift's lucky number!")
"""


while True:
    username = input('Please input your username:')
    if username == 'zhuzhuzhu':
        password = input('Please input your password:')
        p = '000000'
        while password != p:
            password = input('Wrong password !Try again:')
        else:
            print('Welcome ~!')
            while True:
                match_yes = 0
                information = input('Please input the name which you want to search:')
                C = open('info.txt')  # 文件操作
                while True:
                    line = C.readline()  # readline()读取文件中每一行的信息
                    if len(line) == 0:
                        break  # 防止无限循环,当行长度为0,说明信息已经被遍历完了
                    if information in line:
                        print(line)
                        match_yes = 1
                if match_yes == 0:
                    print("No match item found.")
    else:
        print('Sorry, user %s is not found' % username)

该脚本应该注意的问题

while True:
                    line = C.readline()  # readline()读取文件中每一行的信息
                    if len(line) == 0:
                        break  # 防止无限循环,当行长度为0,说明信息已经遍历完了

                    【if information in line:
                        print(line)
                        match_yes = 1
                  if match_yes == 0:
                    print("No match item found.")】

      上面用【】括的那部分代码,如果换用以下方式来表达,会出现输出多条“No match item found.”的问题。
      法1if information in line:
                         print(line)
                     else:
                         print("No match item found.")



这样会导致输出多条No match item found. 这是由于,每遍历一次学生信息,就执行一次循环,而每次循环都会进行一次输出。
===================================================================
      法2if information in line:
                         print(line)
                         match = ‘YES’ 
                   else:
                        pass
                   if match != ‘YES’:
                         print("No match item found.")

这样会出现match未定义的问题,而且!同样也会出现法1中的问题!
关于未定义问题的解释:
当输入的名字在文件中不处于第一行,则第一次循环中并没有对match赋值,转而执行else后面的内容,而else后是pass,因此,当执行下一个if语句时,match依旧没有被赋值,因此会报错。

* 该脚本中未解决的问题*

如果输入姓名时,先敲了一个空格,按理应该不能影响查询,但是!事实上,此功能在上述脚本中并没有得到很好的解决!


文件处理

==

文件的读写-读

1.除了用open来打开文件,也可以用file,使用file之前,需要先在程序开始部分导入Tab模块

import tab
......
C = file("info.txt",'r')  r是只读模式
line = C.readline()
......
C.close  只有将文件关闭,内存才能被释放

文件的读写-写

首先要先再次打开文件:

f = file("info.txt",'w')    w是写入模式,创建新文件或者覆盖原文件
f.write("Hello,my name is alex !! ")
f.write("Hello,my name is alex !! ")    写入文件

打开文件之后发现不显示“Hello,my name is alex !! ”,这是由于写入字符不足1024bit默认将其写到内存中,如果想要读取,用 f.flush()将其刷新到硬盘中,只要不是重新打开文件,就可以write多行,且使用f.flush()不会引起文件内容覆盖。
# f.flush()
# f.close

追加模式 在原来文件的基础上添加内容 ‘a’

f = file("info.txt",'a')
f.write("hello world")
f.flush()

文件读写时遇到的问题:【血泪教训..】

Problem 1

f = open('info.txt')
line = f.readlines()
f.write("hello world")
f.flush()

这里写图片描述

出现上述报错,这是由于,open打开文件默认是只读模式,因此不能向文件中 写入数据。

Problem 2

f = open('info.txt', 'w')
line = f.readlines()
f.write("hello world")
f.flush()

这里写图片描述

将文件模式改为’w’,发现又出现了不可读的问题,并且,当打开文件时发现,文件变成一个空白文件。
这说明,’w’表示创建一个新文件或者覆盖原文件。

然鹅啊。。。天知道按道理我写入hello world,并且用f.flush()刷新之后为什么我的文件里不出现hello world这几个大字!!OMG..


文件的改写

import fileinput
for line in fileinput.input("info.txt", inplace=1):
    line = line.replace("zhuzhuzhu", "liuliuliu")
    print(line)

通过以上,实现了将zhuzhuzhu改写为liuliuliu。

import fileinput
for line in fileinput.input("info.txt", backup='bak', inplace=1):
    line = line.replace("liuliuliu", "hahaha")
    print(line),

加入backup = “bak”,相当于对原文件做了备份。具体见图:

这里写图片描述

相比原来,多了一个TXTBAK文件。

注意
在Python 2中 :
print结尾如果有逗号,表示打印出来的结果不会换行。
在Python 3中:
需要给print后面添加一个参数end=”“,默认不换行

文件的修改

with open('info.txt', 'r+') as f:
    old = f.read()
    f.seek(10)
    m = f.write('new line')

这里写图片描述

with open(‘info.txt’, ‘r+’) as f:等同于f = open(‘info.txt’),’r+’表示文件的读写

文件的定位

语法
f.seek(offset[, from])
参数
offset : 偏移量,即偏移的字节数
from:默认值为 0,给offset参数一个定义,表示开始偏移的位置->->
0代表从文件开头算起,1代表从当前位置算起,2代表从文件末尾算起。

seek(10)表示从文件开头位置开始偏移10个字符,然后进行改写。

列表

  • 创建一个列表:

    nameList = [‘zhuzhuzhu’, ‘guoguoguo’, ‘fufufu’, ‘yanyanyan’, ‘caocaocao’, ‘jinjinjin’]

  • 查询列表元素
    me = nameList[0]

  • 添加列表元素

    • 添加到列表末尾
      nameList.append(‘hahaha’)

    • 插入元素到指定位置
      nameList.insert(2, ‘hahaha’)
      (两个参数:第一个参数表示元素在列表中的位置【索引】,第二个参数表示要插入的列表元素)

  • 列表的计数(计算某一元素在列表中出现的次数)
    nameList.count(‘zhuzhuzhu’)

  • 列表的索引(返回元素在列表中的位置)
    nameList.index(‘zhuzhuzhu’)

  • 列表的删除

    • nameList.remove(‘zhuzhuzhu’)
      如果列表中有多个相同元素,只删除一个

    • nameList.pop(object)
      用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。
      object表示要移除的列表元素对象

  • 列表的排序
    反向/正向排序:nameList.reverse()
    按字母顺序排序:nameList.sort()

  • 列表元素的修改
    nameList[0] = ‘hello you’
    当列表元素很多,不能直观看出列表的位置时,采用以下方法:
    i = nameList.index(‘zhuzhuzhu’)
    nameList[i] = ‘hello you’

元祖

类似列表,但有一个重要区别!!!
元祖内容一旦确定,
只读不可修改
只读不可修改
只读不可修改
重要的事情要说三遍~
NameList = (‘zhuzhuzhu’, ‘fufufu’, ‘jinjinjin’, ‘caocaocao’)

练习程序 2

1.让用户输入工资
2.输出购物菜单及产品价格
3.计算用户是否可支付
4.输出用户剩余的钱,问用户是否继续购物,如若选择继续,则继续购物,直到钱不够为止
5.如若不够,输出用户还需工作多久才能买得起

wages = input('Please input your wages:')
product = ['MAC', 'iphone', 'cloths', 'coffee', 'latiao']
price_list = [9688, 5000, 438, 35, 10]
shopping_list = []
while True:
    print("The list of our products is here.Look and choose your own things:")
    # product_index = product.index(i)
    for i in product:
        print(i, '\t', price_list[product.index(i)])
    choose_thing = input('Please choose the things that you want to buy:')
    F_choice = choose_thing.strip()  # strip()去掉空格
    if F_choice in product:
        product_price_index = product.index(F_choice)
        product_price = price_list[product_price_index]
        print(F_choice, product_price)
        if int(wages) > product_price:
            shopping_list.append(F_choice)
            print('Add %s into your shop list' % F_choice)
            wages = int(wages) - product_price
            print('Wages left : %d' % wages)
        else:
            if int(wages) < min(price_list):
                print('Sorry, rest of your money cannot buy anything!')
                print('Sorry, you have bought %s' % shopping_list)
                break
            else:
                print('Sorry, you cannot afford this product, please choose anyone else')


else:
    print("Sorry, you don't have enough money now. Work hard and go on !")

上述代码只实现了前面的几个功能,还需继续优化。
除了列表之外,也可以用文件进行以上功能的实现。

f = open('list.txt')
products = []
prices = []
shop_list = []
for line in f.readlines():  # 读取文件中的每一行
    new_line = line.split()
    products.append(new_line[0])
    prices.append(int(new_line[1]))
salary = int(input('Please input your salary:'))
while True:
    print("Welcome, things you what to buy as below:")
    for p in products:
        p_index = products.index(p)
        p_price = prices[p_index]
        print(p, p_price)
    choice = input("Please input what you want to buy:")
    f_choice = choice.strip()
    if f_choice in products:
        print("\033[36;1mYes, it is in the list ! \033[0m")
        f_index = products.index(f_choice)
        f_price = prices[f_index]
        if salary >= f_price:
            print("\033[34;1mCongratulations, add %s to your list\033[0m" % f_choice)
            shop_list.append(f_choice)
            salary = salary - f_price
            print("Now you have %d left ! Keep buying~" % salary)
        else:
            if salary < min(prices):
                print("\033[31;1mYou can not buy anything ! Bye ! \033[0m")
                print("You have bought : ", shop_list)
                break
            else:
                print("\033[32;1mSorry, money is not enough to buy %s, please try another one ! ")
    else:
        print("\033[36;1mSorry, %s is not in the list ! Please try anything else ! \033[0m" % f_choice)

总结与收获:
scrip() 去掉空格
split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串。
其中,分隔符默认为所有的空字符,num表示分割次数。

字典

shop = {'car': 20000, 'coffee': 35, 'MAC': 10000, 'iPhone': 5999}
# 字典的键
f = shop.keys()
# 字典的键值对
m = shop.items()
print(f)
print(m)
# 遍历字典中的keys
for i in shop:
    print(i)
# 遍历字典中的键和值
for p, price in shop.items():
    print(p, price)

小程序:用字典改写之前的学生信息表

f = open('info.txt')
contact_dict = {}
for line in f.readlines():
    name = line.split()[1]
    contact_dict[name] = line  # 添加/修改
for n, v in contact_dict.items():
    print('%s \t %s' % (n, v), end='')
while True:
    info_input = input("Please input the staff name:").strip()
    if len(info_input) == 0:
        continue
    if contact_dict.__contains__(info_input):
        print("%s" % contact_dict[info_input])
    else:
        print("Sorry, no staff name found ! ")
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值