Python_oldboy_自动化运维之路(三)

时间:2021-12-07 06:01:52

本节内容

  1. 列表,元组,字典
  2. 字符串操作
  3. copy的用法
  4. 文件操作

1.列表,元组,字典

【列表】

1.定义列表

1 names = ['Alex',"Tenglan",'Eric']

2.通过下标访问列表中的元素,下标从0开始计数

1 >>> names[0]
2 'Alex'
3 >>> names[2]
4 'Eric'
5 >>> names[-1]
6 'Eric'
7 >>> names[-2] #还可以倒着取
8 'Tenglan'

切片:取多个元素

Python_oldboy_自动化运维之路(三)Python_oldboy_自动化运维之路(三)
 1 >>> names = ["Alex","Tenglan","Eric","Rain","Tom","Amy"]
2 >>> names[1:4] #取下标1至下标4之间的数字,包括1,不包括4
3 ['Tenglan', 'Eric', 'Rain']
4 >>> names[1:-1] #取下标1至-1的值,不包括-1
5 ['Tenglan', 'Eric', 'Rain', 'Tom']
6 >>> names[0:3]
7 ['Alex', 'Tenglan', 'Eric']
8 >>> names[:3] #如果是从头开始取,0可以忽略,跟上句效果一样
9 ['Alex', 'Tenglan', 'Eric']
10 >>> names[3:] #如果想取最后一个,必须不能写-1,只能这么写
11 ['Rain', 'Tom', 'Amy']
12 >>> names[3:-1] #这样-1就不会被包含了
13 ['Rain', 'Tom']
14 >>> names[0::2] #后面的2是代表,每隔一个元素,就取一个
15 ['Alex', 'Eric', 'Tom']
16 >>> names[::2] #和上句效果一样
17 ['Alex', 'Eric', 'Tom']
View Code

追加

Python_oldboy_自动化运维之路(三)Python_oldboy_自动化运维之路(三)
1 >>> names
2 ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy']
3 >>> names.append("我是新来的")
4 >>> names
5 ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的']
View Code

插入

Python_oldboy_自动化运维之路(三)Python_oldboy_自动化运维之路(三)
1 >>> names
2 ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的']
3 >>> names.insert(2,"强行从Eric前面插入")
4 >>> names
5 ['Alex', 'Tenglan', '强行从Eric前面插入', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的']
6
7 >>> names.insert(5,"从eric后面插入试试新姿势")
8 >>> names
9 ['Alex', 'Tenglan', '强行从Eric前面插入', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']
View Code

修改

Python_oldboy_自动化运维之路(三)Python_oldboy_自动化运维之路(三)
1 >>> names
2 ['Alex', 'Tenglan', '强行从Eric前面插入', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']
3 >>> names[2] = "该换人了"
4 >>> names
5 ['Alex', 'Tenglan', '该换人了', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']
View Code

删除

Python_oldboy_自动化运维之路(三)Python_oldboy_自动化运维之路(三)
 1 >>> del names[2] 
2 >>> names
3 ['Alex', 'Tenglan', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']
4 >>> del names[4]
5 >>> names
6 ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的']
7 >>>
8 >>> names.remove("Eric") #删除指定元素
9 >>> names
10 ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', '我是新来的']
11 >>> names.pop() #删除列表最后一个值
12 '我是新来的'
13 >>> names
14 ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy']
View Code

扩展

Python_oldboy_自动化运维之路(三)Python_oldboy_自动化运维之路(三)
1 >>> names
2 ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy']
3 >>> b = [1,2,3]
4 >>> names.extend(b)
5 >>> names
6 ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]
View Code

拷贝

Python_oldboy_自动化运维之路(三)Python_oldboy_自动化运维之路(三)
1 >>> names
2 ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]
3
4 >>> name_copy = names.copy()
5 >>> name_copy
6 ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]
View Code

统计

Python_oldboy_自动化运维之路(三)Python_oldboy_自动化运维之路(三)
1 >>> names
2 ['Alex', 'Tenglan', 'Amy', 'Tom', 'Amy', 1, 2, 3]
3 >>> names.count("Amy")
4 2
View Code

排序&翻转

Python_oldboy_自动化运维之路(三)Python_oldboy_自动化运维之路(三)
 1 >>> names
2 ['Alex', 'Tenglan', 'Amy', 'Tom', 'Amy', 1, 2, 3]
3 >>> names.sort() #排序
4 Traceback (most recent call last):
5 File "<stdin>", line 1, in <module>
6 TypeError: unorderable types: int() < str() #3.0里不同数据类型不能放在一起排序了,擦
7 >>> names[-3] = '1'
8 >>> names[-2] = '2'
9 >>> names[-1] = '3'
10 >>> names
11 ['Alex', 'Amy', 'Amy', 'Tenglan', 'Tom', '1', '2', '3']
12 >>> names.sort()
13 >>> names
14 ['1', '2', '3', 'Alex', 'Amy', 'Amy', 'Tenglan', 'Tom']
15
16 >>> names.reverse() #反转
17 >>> names
18 ['Tom', 'Tenglan', 'Amy', 'Amy', 'Alex', '3', '2', '1']
View Code

获取下标

Python_oldboy_自动化运维之路(三)Python_oldboy_自动化运维之路(三)
1 >>> names
2 ['Tom', 'Tenglan', 'Amy', 'Amy', 'Alex', '3', '2', '1']
3 >>> names.index("Amy")
4 2 #只返回找到的第一个下标
View Code

案例1:如何删除列表重复的第二个值,默认只会删除第一个。

Python_oldboy_自动化运维之路(三)Python_oldboy_自动化运维之路(三)
 1 #删除重复第二个b
2 names=["a","b","c","d","b"]
3 print(names)
4
5 first=names.index("b")
6 print(first)
7
8 print(names[first:])
9 print(names[first+1:])
10
11 second=names[first+1:].index("b")
12 print(second)
13
14 del names[first+second+1]
15 print(names)
View Code

 

【元组】

元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表

1 names = ("alex","jack","eric")

它只有2个方法,一个是count,一个是index,完毕。

 

案例1:如何在列表中添加索引。

1 for i,v in enumerate(range(3,10)):
2 print(i,v)
0 3
1 4
2 5
3 6
4 7
5 8
6 9

Process finished with exit code 0

案例2:

#-----------readme------------
#打印省,市,县三级菜单
#b可以返回上一级
#quit退出
Python_oldboy_自动化运维之路(三)Python_oldboy_自动化运维之路(三)
# -*- coding: UTF-8 -*-
#
blog:http://www.cnblogs.com/linux-chenyang/

location
= {
"北京":{
"海淀":{
"西二旗":"新浪",
"中关村":"爱奇艺"
},
"昌平":{
"回龙观":"煎饼果子",
"沙河":"老男孩"
}
},
"内蒙":{
"呼和浩特":{
"火车站":"伊利",
"汽车站":"蒙牛"
},
"巴彦淖尔":{
"渡口":"苏木井",
"协成":"大棚"
}
}
}
flag
= True

while flag:
for i in location:
print(i)
choice
= input(">>:").strip()
if choice in location:
location_1
= location[choice]
# print(location_1)
while flag:
for k in location_1:
print(k)
choice2
= input("继续选择>>:")
if choice2 in location_1:
location_2
= location[choice][choice2]
for z in location_2:
print(z)

elif choice2 == "b":
break
elif choice2 == "quit":
flag
= False
break
elif choice == "quit":
flag
= False
else:
print("输入错误,请重新输入.....

案例3:程序:购物车程序

需求:

  1. 启动程序后,让用户输入工资,然后打印商品列表
  2. 允许用户根据商品编号购买商品
  3. 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 
  4. 可随时退出,退出时,打印已购买商品和余额
 1 #!/usr/bin/python
2 # -*- coding: UTF-8 -*-
3 #blog:http://www.cnblogs.com/linux-chenyang/
4 #
5 #----------------readme-------------------------
6 #1.启动程序后输入你的工资,然后打印商品列表。
7 #2.如果选择的是列表内的商品,则进行下一步,否则提示没有这个商品。
8 #3.如果选择的商品小于工资,则显示余额,大于工资则显示还差多少钱。
9 #4.选择exit退出并且显示消费的钱和余额。
10
11 product_list = [
12 ["Iphone7",6500],
13 ["MackBook",12000],
14 ["Python book",60],
15 ["Bike",300],
16 ["coffee",30],
17 ]
18 shoppint_cart = []
19
20 salary = int(input("Please youer salary:"))
21 while True:
22 for index,i in enumerate(product_list):
23 print("%s.\t%s\t%s" %(index,i[0],i[1]))                      #\t表示空格。
24 choice = input(">>:").strip()                              #strip()表示去除空格。
25 if choice.isdigit():                                   #isdigit()检测字符串是否只由数字组成。
26 choice = int(choice)
27 if choice < len(product_list) and choice >=0:
28 product_item = product_list[choice]                      #选择的商品
29 if salary >= product_item[1]:
30 salary -= product_item[1]                          #剩余的钱
31 shoppint_cart.append(product_item)                    #添加至购物车
32
33 print("%s已经加入到你的购物车,余额还剩%s" %(product_item[0],salary))
34 else:
35 print("对不起你的余额不足,还差",product_item[1]-salary)          #商品价格减去剩余的钱就少还差多少钱
36 else:
37 print("没有这个商品!")
38
39 elif choice == "exit":
40 total_cost = 0
41 print("你已经添加到购物车的东西是:")
42 for i in shoppint_cart:
43 print(i)
44 total_cost += i[1]                                 #循环加购物车里的钱
45 print("您总共消费为",total_cost )
46 print("您的余额是", salary)
47 break
48
49 else:
50 print("非法的输入,请选择商品序号或者退出exit")
Please youer salary:5000
0. Iphone7
6500
1. MackBook 12000
2. Python book 60
3. Bike 300
4. coffee 30
>>:2
Python book已经加入到你的购物车,余额还剩4940
0. Iphone7
6500
1. MackBook 12000
2. Python book 60
3. Bike 300
4. coffee 30
>>:3
Bike已经加入到你的购物车,余额还剩4640
0. Iphone7
6500
1. MackBook 12000
2. Python book 60
3. Bike 300
4. coffee 30
>>:4
coffee已经加入到你的购物车,余额还剩4610
0. Iphone7
6500
1. MackBook 12000
2. Python book 60
3. Bike 300
4. coffee 30
>>:3
Bike已经加入到你的购物车,余额还剩4310
0. Iphone7
6500
1. MackBook 12000
2. Python book 60
3. Bike 300
4. coffee 30
>>:exit
你已经添加到购物车的东西是:
[
'Python book', 60]
[
'Bike', 300]
[
'coffee', 30]
[
'Bike', 300]
您总共消费为
690
您的余额是
4310

Process finished with exit code 0

【字典】

字典一种key - value 的数据类型,使用就像我们上学用的字典,通过笔划、字母来查对应页的详细内容。

  • dict是无序的
  • key必须是唯一的,so 天生去重
  • 字典的查询速度比列表快(原因:使用了hash算法,中文叫撒列,比如字典name:lijun,通过name如何快速的找到lijun,其实是先将name利用hash转换成数值,然后在利用二分查找,先排序,取一半判断是大于这个数值还是小于这个数值,小于在左边,大于在右边,然后在取半)

循环dict

#方法1
for key in info:
print(key,info[key])

#方法2
for k,v in info.items(): #会先把dict转成list,数据里大时莫用
print(k,v)

 

 1 names = {
2 "18788888888":{"name":"chenlijun","age":22,"hobbie":"girl",},
3 "18266666666":"lijun",
4 "13499999999":"xiaoyu",
5 }
6
7 #search
8 print(names)
9 print(names["18788888888"])
10 print(names["18788888888"]["hobbie"])
11 print(names.get("12345678","87654321"))
12
13 #add
14 names["12345678"] = ["zhouxingchi","50","DBA"]
15 print(names)
16
17 #update
18 names["12345678"][0] = "xingye"
19 print(names)
20
21 #del
22 print(names.pop("12345678"))
23 print(names)
24 print(names.pop("111111111","没有这个号码"))
25 del names["18266666666"]
26 print(names)
{'18788888888': {'age': 22, 'hobbie': 'girl', 'name': 'chenlijun'}, '13499999999': 'xiaoyu', '18266666666': 'lijun'}
{
'age': 22, 'hobbie': 'girl', 'name': 'chenlijun'}
girl
87654321
{
'18788888888': {'age': 22, 'hobbie': 'girl', 'name': 'chenlijun'}, '13499999999': 'xiaoyu', '18266666666': 'lijun', '12345678': ['zhouxingchi', '50', 'DBA']}
{
'18788888888': {'age': 22, 'hobbie': 'girl', 'name': 'chenlijun'}, '13499999999': 'xiaoyu', '18266666666': 'lijun', '12345678': ['xingye', '50', 'DBA']}
[
'xingye', '50', 'DBA']
{
'18788888888': {'age': 22, 'hobbie': 'girl', 'name': 'chenlijun'}, '13499999999': 'xiaoyu', '18266666666': 'lijun'}
没有这个号码
{
'18788888888': {'age': 22, 'hobbie': 'girl', 'name': 'chenlijun'}, '13499999999': 'xiaoyu'}

Process finished with exit code 0

案例1:高富帅版本

#-----------readme------------
#打印省,市,县三级菜单
#b可以返回上一级
#quit退出
Python_oldboy_自动化运维之路(三)Python_oldboy_自动化运维之路(三)
 1 # -*- coding: UTF-8 -*-
2 #blog:http://www.cnblogs.com/linux-chenyang/
3
4 menu = {
5 '北京':{
6 '海淀':{
7 '西二旗':["新浪","网易","百度"],
8 '上地':["爱奇艺","优酷","土豆"]
9 },
10 '昌平':{
11 '沙河':["老男孩","沙县小吃"],
12 '回龙观':["龙锦苑","兰州拉面"]
13 }
14 },
15 '内蒙古':{
16 '呼和浩特':{
17 '企业':["蒙牛","伊利"],
18 '车站':["火车站","汽车站"]
19 },
20 '巴彦淖尔':{
21 '地理':["草原","沙漠"],
22 '特色':["华莱士","番茄"]
23 }
24
25 }
26 }
27
28 layer = menu
29 p_layer = []
30
31 while True:
32 for k in layer:
33 print(k)
34 choice = input(">:").strip()
35 if len(choice) == 0:continue
36
37 if choice in layer:
38 p_layer.append(layer)
39 layer = layer[choice]
40
41 elif choice == "b":
42 if len(p_layer) > 0:
43 layer = p_layer.pop()
44 elif choice == "q":
45 exit()
View Code
 

 

 

2.字符串操作

特性:不可修改 

name.capitalize()  首字母大写
name.casefold() 大写全部变小写
name.center(
50,"-") 输出 '---------------------Alex Li----------------------'
name.count(
'lex') 统计 lex出现次数
name.encode() 将字符串编码成bytes格式
name.endswith(
"Li") 判断字符串是否以 Li结尾
"Alex\tLi".expandtabs(10) 输出'Alex Li', 将\t转换成多长的空格
name.find(
'A') 查找A,找到返回其索引, 找不到返回-1

format :
>>> msg = "my name is {}, and age is {}"
>>> msg.format("alex",22)
'my name is alex, and age is 22'
>>> msg = "my name is {1}, and age is {0}"
>>> msg.format("alex",22)
'my name is 22, and age is alex'
>>> msg = "my name is {name}, and age is {age}"
>>> msg.format(age=22,name="ale")
'my name is ale, and age is 22'
format_map
>>> msg.format_map({'name':'alex','age':22})
'my name is alex, and age is 22'


msg.index(
'a') 返回a所在字符串的索引
'9aA'.isalnum() True

'9'.isdigit() 是否整数
name.isnumeric
name.isprintable
name.isspace
name.istitle
name.isupper
"|".join(['alex','jack','rain'])
'alex|jack|rain'


maketrans
>>> intab = "aeiou" #This is the string having actual characters.
>>> outtab = "12345" #This is the string having corresponding mapping character
>>> trantab = str.maketrans(intab, outtab)
>>>
>>> str = "this is string example....wow!!!"
>>> str.translate(trantab)
'th3s 3s str3ng 2x1mpl2....w4w!!!'

msg.partition(
'is') 输出 ('my name ', 'is', ' {name}, and age is {age}')

>>> "alex li, chinese name is lijie".replace("li","LI",1)
'alex LI, chinese name is lijie'

msg.swapcase 大小写互换


>>> msg.zfill(40)
'00000my name is {name}, and age is {age}'



>>> n4.ljust(40,"-")
'Hello 2orld-----------------------------'
>>> n4.rjust(40,"-")
'-----------------------------Hello 2orld'


>>> b="ddefdsdff_哈哈"
>>> b.isidentifier() #检测一段字符串可否被当作标志符,即是否符合变量命名规则
True

 3.copy的用法

第一层的数据不会跟着变,第二层后的数据会跟着变。

 

 1 names = {
2 "18788888888":{"name":"chenlijun","age":22},
3 "18266666666":"lijun",
4 "13499999999":"xiaoyu",
5 }
6
7 n2 = names.copy()
8 print(names)
9 print(n2)
10
11 names["18266666666"] = "LIJUN"
12 print(names)
13 print(n2)
14
15 names["18788888888"]["age"] = 24
16 print(names)
17 print(n2)

 

{'13499999999': 'xiaoyu', '18788888888': {'name': 'chenlijun', 'age': 22}, '18266666666': 'lijun'}
{
'13499999999': 'xiaoyu', '18788888888': {'name': 'chenlijun', 'age': 22}, '18266666666': 'lijun'}

{
'13499999999': 'xiaoyu', '18788888888': {'name': 'chenlijun', 'age': 22}, '18266666666': 'LIJUN'}
{
'13499999999': 'xiaoyu', '18788888888': {'name': 'chenlijun', 'age': 22}, '18266666666': 'lijun'}

{
'13499999999': 'xiaoyu', '18788888888': {'name': 'chenlijun', 'age': 24}, '18266666666': 'LIJUN'}
{
'13499999999': 'xiaoyu', '18788888888': {'name': 'chenlijun', 'age': 24}, '18266666666': 'lijun'}

案例1:银行的共享账户。

 1 credit_card = {"name":"至尊宝","acc":{"id":6210222,"balance":900}}
2 credit_card2 = credit_card.copy()
3
4 credit_card2["name"] = "紫霞仙子"
5
6 print(credit_card)
7 print(credit_card2)
8
9
10 credit_card["acc"]["balance"] -= 300
11 print(credit_card)
12 print(credit_card2)
13
14 credit_card2["acc"]["balance"] -= 500
15 print(credit_card)
16 print(credit_card2)
{'name': '至尊宝', 'acc': {'balance': 900, 'id': 6210222}}
{
'name': '紫霞仙子', 'acc': {'balance': 900, 'id': 6210222}}

{
'name': '至尊宝', 'acc': {'balance': 600, 'id': 6210222}}
{
'name': '紫霞仙子', 'acc': {'balance': 600, 'id': 6210222}}

{
'name': '至尊宝', 'acc': {'balance': 100, 'id': 6210222}}
{
'name': '紫霞仙子', 'acc': {'balance': 100, 'id': 6210222}}

 4.文件操作

对文件操作流程

  1. 打开文件,得到文件句柄并赋值给一个变量
  2. 通过句柄对文件进行操作
  3. 关闭文件

打开文件的模式有:

  • r,只读模式(默认)。
  • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
  • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+,可读写文件。【可读;可写;可追加】
  • w+,写读
  • a+,同a

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)

  • rU
  • r+U

"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

  • rb
  • wb
  • ab

【r,w,a的用法】

案例1:创建一个文件,并且写入内容,会在同一个目录里创建一个lyrie文件。

1 f = open("lyrie",mode="a",encoding="utf-8")
2
3 f.write("\nPlease input send str...")
4 f.write("\nPlease input send str...")
5 f.write("\nPlease input send str...")
6
7 f.close()

Python_oldboy_自动化运维之路(三)

案例2:替换文件里的内容(这种方法b弊端:太吃服务器的内存)

 1 f = open("lyrie",mode="r",encoding="utf-8")
2
3 date = f.read()
4 date = date.replace("input","hahahhha")
5 f.close()
6
7 f = open("lyrie",mode="w",encoding="utf-8")
8
9 f.write(date)
10 f.close()

Python_oldboy_自动化运维之路(三)

案例3:如果只修改一个字符串,可以循环一行行读,然后写到新的文件里,将原文件删除,新文件改成原文件的名字。(弊端:占用两倍硬盘空间)

 1 import os                       #导入模块
2
3 f = open("lyrie",mode="r",encoding="utf-8")
4
5 f_new = open("lyrie_new",mode="w",encoding="utf-8")
6
7 for line in f:
8 print(line) #循环一行行读
9 if "Please" in line:
10 line = line.replace("Please","aaa")
11
12 f_new.write(line)
13
14 f.close()
15 f_new.close()
16
17 os.remove("lyrie")
18 os.rename("lyrie_new","lyrie")

Python_oldboy_自动化运维之路(三)

 【r+,w+,a+的用法】

1.r+在原因的文件追加,可读;a只能追加,可以定长修改,利用seek()的方法。

# -*- coding: UTF-8 -*-
#
blog:http://www.cnblogs.com/linux-chenyang/

f
= open("lyrie","r+",encoding="utf-8")
print(f.read())
f.write(
"--------test------")
f.close()

Python_oldboy_自动化运维之路(三)

Python_oldboy_自动化运维之路(三)

 2.w+,清空原文件内容,在写入新的内容。

# -*- coding: UTF-8 -*-
#
blog:http://www.cnblogs.com/linux-chenyang/

f
= open("lyrie","w+",encoding="utf-8")
print(f.read())
f.write(
"--------test------")
f.close()

Python_oldboy_自动化运维之路(三)

知识点:read()

a.读完后在读一次,发现在读不了了,说明read类似有个光标的功能,光标走到底在读就没有了。

# -*- coding: UTF-8 -*-
#
blog:http://www.cnblogs.com/linux-chenyang/
f = open("lyrie","r",encoding="utf-8")
print(f.read())
print("--------------------------")
print(f.read())              

Python_oldboy_自动化运维之路(三)

b.怎么看光标在那个位置。

# -*- coding: UTF-8 -*-
#
blog:http://www.cnblogs.com/linux-chenyang/
f = open("lyrie","r",encoding="utf-8")
print('cursor:',f.tell())
print(f.read())
print('cursor:',f.tell())
print("--------------------------")
print(f.read())
print('cursor:',f.tell())

Python_oldboy_自动化运维之路(三)

c.移动光标位置。

# -*- coding: UTF-8 -*-
#
blog:http://www.cnblogs.com/linux-chenyang/
f = open("lyrie","r",encoding="utf-8")
print('cursor:',f.tell())
f.seek(
10) #代表移动10个字节,不是10个字符。
print('cursor:',f.tell())
print(f.read(5)) #读的时候是字符,5个字符。

Python_oldboy_自动化运维之路(三)

3.a+,可以追加,读。

# -*- coding: UTF-8 -*-
#
blog:http://www.cnblogs.com/linux-chenyang/

f
= open("lyrie","a+",encoding="utf-8")
f.write(
"--------哈哈------")
f.seek(0)
print(f.read())
f.close()

Python_oldboy_自动化运维之路(三)

【rb的用法】

f = open("lyrie","rb")
print(f.read())
f.close()

Python_oldboy_自动化运维之路(三)

知识点:import sys

# -*- coding: UTF-8 -*-
#
blog:http://www.cnblogs.com/linux-chenyang/

import sys

print(sys.argv)

oldstr
= sys.argv[1]
newstr
= sys.argv[2]

print(oldstr,newstr)

Python_oldboy_自动化运维之路(三)

其他语法:

def close(self): # real signature unknown; restored from __doc__
"""
Close the file.

A closed file cannot be used for further I/O operations. close() may be
called more than once without error.
"""
pass

def fileno(self, *args, **kwargs): # real signature unknown
""" Return the underlying file descriptor (an integer). """
pass

def isatty(self, *args, **kwargs): # real signature unknown
""" True if the file is connected to a TTY device. """
pass

def read(self, size=-1): # known case of _io.FileIO.read
"""
注意,不一定能全读回来
Read at most size bytes, returned as bytes.

Only makes one system call, so less data may be returned than requested.
In non-blocking mode, returns None if no data is available.
Return an empty bytes object at EOF.
"""
return ""

def readable(self, *args, **kwargs): # real signature unknown
""" True if file was opened in a read mode. """
pass

def readall(self, *args, **kwargs): # real signature unknown
"""
Read all data from the file, returned as bytes.

In non-blocking mode, returns as much as is immediately available,
or None if no data is available. Return an empty bytes object at EOF.
"""
pass

def readinto(self): # real signature unknown; restored from __doc__
""" Same as RawIOBase.readinto(). """
pass #不要用,没人知道它是干嘛用的

def seek(self, *args, **kwargs): # real signature unknown
"""
Move to new file position and return the file position.

Argument offset is a byte count. Optional argument whence defaults to
SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
are SEEK_CUR or 1 (move relative to current position, positive or negative),
and SEEK_END or 2 (move relative to end of file, usually negative, although
many platforms allow seeking beyond the end of a file).

Note that not all file objects are seekable.
"""
pass

def seekable(self, *args, **kwargs): # real signature unknown
""" True if file supports random-access. """
pass

def tell(self, *args, **kwargs): # real signature unknown
"""
Current file position.

Can raise OSError for non seekable files.
"""
pass

def truncate(self, *args, **kwargs): # real signature unknown
"""
Truncate the file to at most size bytes and return the truncated size.

Size defaults to the current file position, as returned by tell().
The current file position is changed to the value of size.
"""
pass

def writable(self, *args, **kwargs): # real signature unknown
""" True if file was opened in a write mode. """
pass

def write(self, *args, **kwargs): # real signature unknown
"""
Write bytes b to file, return number written.

Only makes one system call, so not all of the data may be written.
The number of bytes actually written is returned. In non-blocking mode,
returns None if the write would block.
"""
pass

   flush() 强制从内存中写入到硬盘,不用close,可以减少硬盘的读取操作。