1 笔记记录:
2 1、#交互,输入name
3 name = raw_input('what is your name?')
4 #实现多行交互输入,输入Q结束输入
5 user_date=''
6 stopword='Q'
7 with open("tmp.txt",'w') as f:
8 for line in iter(raw_input,stopword):
9 user_date = line +'\n'
10 f.write(user_date)
11
12 2、#读取文件存入到account_list , 后面是写入
13 f = file(account_file)
14 account_list = f.readlines()
15 f.close()
16
17 f = file(account_file,'a') # a代表追加 ,如果用w 就是覆盖
18 f.write('\n%s' % username)
19 f.close()
20
21 # 实时地写进去文件里
22 f.flush()
23
24 3、循环转换成数组.split()
25 for line in account_list:
26 line = line.split()
27
28 4、三次循环,break是退出,continue继续:
29 for i in range(3):
30 if i == 3: break
31 else continue
32
33 5、fileinput的具体用法是:
34 fileinput.FileInput(files=None, inplace=False, backup='', bufsize=0, mode='r', openhook=None)
35 其中:
36 files :文件的路径列表;
37 inplace:是否将标准输出(print方法)的结果写回文件;
38 backup : 备份文件的扩展名;
39 bufsize :缓冲区大小;
40 mode :读写模式;
41 openhook : 打开文件时的钩子;
42
43 6、文件打开处理:
44 f = f.file("f_test.txt")
45 f.readlines()
46 f.tell() # 当前的位置
47 f.seek(0) # 回到指定的行数位置
48
49 f.truncate(100) # 截取到100的位置
50
51 # 相当于f = f.file("f_test.txt")打开,但不需要用关闭的。
52 with open("f_test.txt",'r+') as f:
53 f.seek(24)
54 f.truncate(30)
55
56 f.flush() 方法是用来刷新缓冲区,一般情况下,文件关闭后会自动刷新缓冲区,但有时你需要在关闭前刷新他它,这时就可以使用flush()方法。
57
58 7、列表
59 name_list[]
60 name_list.index(20) # 代表列表中数值20所在的位置
61 name_list.insert(1,'Rain') # 往列表1位置 插入数值'Rain',后面的值往后排
62 name_list.remove('Rain') # 删除列表中第一个Rain值
63 name_list.count('Rain') # 自带统计有多少个Rain值
64 name_list.sort() # 列表的排序
65 name_list.pop() # 删除列表最后一个内容
66 name_list.extend('[7,8,9]') # 按照列表格式加入
67 name_list[4] = 'CHECK' # 修改列表第四个的内容
68 name_list[2:7] #切片, 第2内容到7内容,不包含7
69 name_list[7:] #第7个后面的内容
70 name_list[-5:] #切片倒数第五个及其后面内容
71 name_list[1:6:2] #跳着截取,2是步长,截取135内容
72 #把列表一行打印,按照指定的分隔符'|'
73 from __future__ import print_function
74 names = ["Sam", "Peter", "James", "Julian", "Ann"]
75 print(*names,sep='|')
76
77
78 8、read() readline() readlines()
79 read() # 每单个字符读取
80 readline() # 每行读取,存入的是字符串行
81 readlines() # 每行读取,存入的是列表行
82
83 9、startswith()
84 Python startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。
85 line.startswith(str, beg=0,end=len(string));
86 参数
87 str -- 检测的字符串。
88 strbeg -- 可选参数用于设置字符串检测的起始位置。
89 strend -- 可选参数用于设置字符串检测的结束位置。
90
91 10、字典
92 contacts = {}
93 # 字典里可以存任何的东西
94 contacts = {
95 'Alex' : 13750362307,
96 'Rachel':[13750362308,'student',25],
97 'Rain' : {'age':28},
98 }
99
100 # 只可以修改values值的内容,不可以修改key值
101 contacts['Alex'] = 199999999999
102
103 # 删除内容
104 del contacts['Rachel']
105
106 # 新增内容
107 contacts['Marry'] = '666666','chiji'
108
109 # 只打印了 key的值
110 for i in contacts:
111 print i
112
113 # 把key和values都打印,但是按照元组来打印
114 for i in contacts.items():
115 print i
116
117 # 把key和values分开打印
118 for x,y in contacts.items():
119 print x,y
120
121 # 查看所有的key
122 print contacts.keys()
123 # 查看所有的values
124 print contacts.values()
125
126 # 查询字典里的内容
127 if contacts.has_key('Alex') : print '666666666'
128
129 11、字体添加颜色:
130 开头部分:\033[显示方式;前景色;背景色m + 结尾部分:\033[0m
131
132 12、对齐打印
133 from prettytable import PrettyTablex = PrettyTable(["名字", "数学成绩", "语文成绩", "计算机成绩"])
134 x.add_row(["小明",200, 199, 198])x.add_row(["大明白",197, 196, 195])x.add_row(["老明亮了", 300, 299, 298])
135 print(x)
136
137 13、函数:
138 (1)返回多个值
139 def returnMulti():
140 return 1, 2, 3
141 result = returnMulti()
142 a, b, c = returnMulti()
143 print result[0], result[1], result[2]
144 print a, b, c
145
146 14、枚举函数
147 枚举函数enumerate 循环访问时,同时访问索引值:
148 for i in enumerate('sdfsifisneamlgljslf;fsdf'):
149 print (i)
150
151
152 python中的SET集合
153 python的set是一个无序不重复元素集,可以用作去重功能的。
154
155 15、from os import system;
156 #导入os模块,可以使用shell命令,调用方式如下:
157 os.system('df') 执行失败的话结果是返回0的。
158 os.popen('df') 执行结果是按照内容返回的。
159
160 16、import sys,datetime
161 #导入sys,datetime模块
162 # 程序退出,直接用sys
163 sys.exit('发生错误,程序退出')
164 # 获取当前系统时间
165 getdate = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
166
167 17、迭代器
168 迭代器一次只产生一个数据项, 占用更加少的内存。
169 迭代器,iter() 只会保留一次, 占用内存很少, 处理大量文件的时候,不建议使用列表,建议使用迭代器进行处理。
170 # 迭代器的方法只有一个 .next()
171 a = [1,2,3,4,5,6,7]
172 b = iter(a)
173 for i in b:print i
174
175 18、lambda 匿名函数,可以理解为单行函数。 使用lambda函数不需要考虑命名函数名。
176 a=lambda i,x : i**2/(x-i)
177
178 19、序列化
179
180 知识 pickle , json
181 序列化 ,就是把内存的东西写到硬盘中。可以存放列表,数组
182 而如果只是用write, write只能写入的是字符串
183 import pickle
184 account_info = {
185 '92392382838':['Alex1234',15000,16000],
186 '29394823472':['Rachel',9000,9000],
187 'Rain':{
188 'age':'30',
189 'job':'salesmen'
190 }
191 }
192 f = file('account.pkl','wb') # 二进制打开文件
193 pickle.dump(account_info,f) # 倾泻到f文件里
194 f.close()
195
196 f = file('account.pkl')
197 abc = pickle.load(f)
198 # pickle是可以dump多次的,但是你需要Load多次才能使用才是你需要的状态,所以一般都只建议dump一次。
199 # 使用xml格式用 跨语言数据交换。 java、python、C#、C
200 # 现在多数使用的是 json 格式进行来数据交换。
201 import json
202 f = file ('account_info.json','wb')
203 json.dump(account_info,f)
204 f.close()
205 f = file('account_info.json')
206 b = json.load(f)
207
208 20、 正则表达式
209 import re
210 p = re.compile('hello')
211 >>> p.match('hello hello work') # 如果匹配不了的话,会返回None
212 <_sre.SRE_Match object at 0x10fcf5a58>
213
214 >>> p.findall('hello hello worerenfn') # 会以列表形式进行存储
215 ['hello', 'hello']
216
217 p = re.compile('\d') # 匹配任何十进制数字;相当于0-9
218 p = re.compile() # 匹配任何非数字字符,相当于^0-9
219 p = re.compile('\d+') # 匹配多个数字
220
221 # 替换
222 >>> re.sub('[a-z]','o','sjndfhsh213nfnj')
223 'oooooooo213oooo'
224 >>> re.sub(r'\d+','o','jdjsfn33n343')
225 'jdjsfnono'
226
227 c = 'jjfs*&'
228 c.isalpha() # 检查是否有特殊字符 ,有的话返回Faluse ,没有的话返回True
229
230
231 --------------------------------------------------------------------------------
232 day1:
233 #!/usr/bin/env python
234
235 print 'hello world!'
236
237 #python 是严格用缩进来规范的。
238 if True:
239 print 'asdasdadad'
240
241 #python 定义变量只能用大小写字母或下划线 _ 开头定义:
242 name = Alex Li #错误:存在空格,另外如果没有加单引号,也会错误
243
244
245 #模块:
246 import myFrist.py as my #别名my
247
248 from os import system;
249 #导入os模块,可以使用shell命令,调用方式如下:
250 os.system('df') 执行失败的话结果是返回0的。
251 os.popen('df') 执行结果是按照内容返回的。
252 --------------------------------------------------------------------------------
253 #交互:
254 #!/usr/bin/env python
255 name = raw_input('what is your name?')
256 age = raw_input('What is your age?')
257 sex = raw_input('What is your job?')
258 #外部引用变量
259 print """Person info:
260
261 Name: %s
262 Age : %s
263 sex : %s
264 Job : %s
265 """ % (name,age,sex,job) #%s 就是一一对应进行外部写入
266 --------------------------------------------------------------------------------
267
268 登录脚本:
269 1、输入正确的账号密码登录
270 2、输错三次密码锁定账号
271
272 #!/usr/bin/env python
273 # -*- coding: UTF-8 -*-
274 # 文件面 : lock.py
275
276
277
278 account_file = 'username.txt'
279 lock_file = 'lock.txt'
280
281 f = file(account_file)
282 account_list = f.readlines()
283 f.close()
284
285 '''
286 f = file(lock_file)
287 lock_list = []
288 for i in f.readlines():
289 line = i.strip('\n') #以\n换行符来做分割
290 lock_list.append(line) # .append() 加入数组里
291 f.close()
292 '''
293 # print lock_list
294
295 # 定义一个参数:
296 loginSuccess = False
297
298
299 while True:
300 username = raw_input('user:').strip()
301 f = file(lock_file)
302 lock_list = []
303 for i in f.readlines():
304 line = i.strip('\n') # 以\n换行符来做分割
305 lock_list.append(line) # .append() 加入数组里
306 f.close()
307 if username in lock_list:
308 print "%s is locked,not allow login!" % username
309 break
310 for line in account_list:
311 line = line.split()
312 if len(username) != 0 and username == line[0]:
313 for i in range(3):
314 passwd = raw_input("password:").strip()
315 if passwd == line[1] :
316 print "welcome %s come in my system!" % username
317 # 改变这个标识,为了识别可以退出循环。
318 loginSuccess = True
319 if loginSuccess is True: break # 为了退出for循环
320 else:
321 continue
322 # 循环三次密码都失败的话,才进入此步:
323 else:
324 print "you put 3 times error password,your username: %s have locked! " %username
325 f = file(lock_file,'a') # a代表追加
326 f.write('\n%s' % username)
327 f.close()
328 #loginSuccess = True # 打上Ture标识,为了可以退出while巡检
329 if loginSuccess is True: break # 为了退出 while巡检
330
331 --------------------------------------------------------------------------------
332 #!/usr/bin/env python
333 # coding=utf-8
334 # 功能:存入字典了,输入进行模糊查询
335 import sys
336
337 employee = {} # 定义一个字典
338 with open('employee.txt','r') as f:
339 for i in f.readlines(): # 每行读取成为以列表形式
340 print i
341 line = i.split('|') # 以分隔符'|' 存入列表
342 employee[line[0]]= line[1:] # 存入到字典里
343 '''
344 for x,y in employee.items(): # 历遍打印keys和values值
345 print x,y
346
347 print employee.keys()
348 '''
349
350 while True:
351 names = raw_input("please send info:")
352 if employee.has_key(names):
353 print names , employee[names]
354 else:
355 info_count = 0
356 if len(names) < 3:
357 print "must names's len more than 3"
358 continue
359 for x , y in employee.items():
360 if x.count(names) != 0:
361 info_count += 1
362 continue
363 print x,'|'.join(y)
364 for i in y:
365 if i.count(names) != 0:
366 print x,'|'.join(y)
367 info_count += 1