A.三元运算
- 三元运算(三目运算),是对简单的条件语句的缩写。
# 书写格式 result = 值1 if 条件 else 值2 # 如果条件成立,那么将 “值1” 赋值给result变量,否则,将“值2”赋值给result变量
B.函数
- 定义函数
def 函数名(参数): ... 函数体 ... 返回值(return)
函数的定义主要有如下要点:
- def:表示函数的关键字
- 函数名:函数的名称,日后根据函数名调用函数
- 函数体:函数中进行一系列的逻辑计算,如:发送邮件、计算出 [11,22,38,888,2]中的最大数等...
- 参数:为函数体提供数据
- 返回值:当函数执行完毕后,可以给调用者返回数据。
- 参数
函数的有三中不同的参数:
- 普通参数
# ######### 定义函数 ######### # name 叫做函数func的形式参数,简称:形参 def func(name): print name # ######### 执行函数 ######### # 'wupeiqi' 叫做函数func的实际参数,简称:实参 func('wupeiqi')
- 默认参数
def func(name, age = 18): print "%s:%s" %(name,age) # 指定参数 func('wupeiqi', 19) # 使用默认参数 func('alex') 注:默认参数需要放在参数列表最后
- 动态参数
def func(*args): print args # 执行方式一 func(11,33,4,4454,5) # 执行方式二 li = [11,2,2,3,3,4,54] func(*li) def func(**kwargs): print args # 执行方式一 func(name='wupeiqi',age=18) # 执行方式二 li = {'name':'wupeiqi', age:18, 'gender':'male'} func(**li) def func(*args, **kwargs): print args print kwargs
C.文件操作
1 class TextIOWrapper(_TextIOBase): 2 """ 3 Character and line based layer over a BufferedIOBase object, buffer. 4 5 encoding gives the name of the encoding that the stream will be 6 decoded or encoded with. It defaults to locale.getpreferredencoding(False). 7 8 errors determines the strictness of encoding and decoding (see 9 help(codecs.Codec) or the documentation for codecs.register) and 10 defaults to "strict". 11 12 newline controls how line endings are handled. It can be None, '', 13 ' ', ' ', and ' '. It works as follows: 14 15 * On input, if newline is None, universal newlines mode is 16 enabled. Lines in the input can end in ' ', ' ', or ' ', and 17 these are translated into ' ' before being returned to the 18 caller. If it is '', universal newline mode is enabled, but line 19 endings are returned to the caller untranslated. If it has any of 20 the other legal values, input lines are only terminated by the given 21 string, and the line ending is returned to the caller untranslated. 22 23 * On output, if newline is None, any ' ' characters written are 24 translated to the system default line separator, os.linesep. If 25 newline is '' or ' ', no translation takes place. If newline is any 26 of the other legal values, any ' ' characters written are translated 27 to the given string. 28 29 If line_buffering is True, a call to flush is implied when a call to 30 write contains a newline character. 31 """ 32 def close(self, *args, **kwargs): # real signature unknown 33 关闭文件 34 pass 35 36 def fileno(self, *args, **kwargs): # real signature unknown 37 文件描述符 38 pass 39 40 def flush(self, *args, **kwargs): # real signature unknown 41 刷新文件内部缓冲区 42 pass 43 44 def isatty(self, *args, **kwargs): # real signature unknown 45 判断文件是否是同意tty设备 46 pass 47 48 def read(self, *args, **kwargs): # real signature unknown 49 读取指定字节数据 50 pass 51 52 def readable(self, *args, **kwargs): # real signature unknown 53 是否可读 54 pass 55 56 def readline(self, *args, **kwargs): # real signature unknown 57 仅读取一行数据 58 pass 59 60 def seek(self, *args, **kwargs): # real signature unknown 61 指定文件中指针位置 62 pass 63 64 def seekable(self, *args, **kwargs): # real signature unknown 65 指针是否可操作 66 pass 67 68 def tell(self, *args, **kwargs): # real signature unknown 69 获取指针位置 70 pass 71 72 def truncate(self, *args, **kwargs): # real signature unknown 73 截断数据,仅保留指定之前数据 74 pass 75 76 def writable(self, *args, **kwargs): # real signature unknown 77 是否可写 78 pass 79 80 def write(self, *args, **kwargs): # real signature unknown 81 写内容 82 pass 83 84 def __getstate__(self, *args, **kwargs): # real signature unknown 85 pass 86 87 def __init__(self, *args, **kwargs): # real signature unknown 88 pass 89 90 @staticmethod # known case of __new__ 91 def __new__(*args, **kwargs): # real signature unknown 92 """ Create and return a new object. See help(type) for accurate signature. """ 93 pass 94 95 def __next__(self, *args, **kwargs): # real signature unknown 96 """ Implement next(self). """ 97 pass 98 99 def __repr__(self, *args, **kwargs): # real signature unknown 100 """ Return repr(self). """ 101 pass 102 103 buffer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 104 105 closed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 106 107 encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 108 109 errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 110 111 line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 112 113 name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 114 115 newlines = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 116 117 _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 118 119 _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
- 打开文件
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
打开文件的模式有:
r ,只读模式【默认模式,文件必须存在,不存在则抛出异常】
w,只写模式【不可读;不存在则创建;存在则清空内容】
x, 只写模式【不可读;不存在则创建,存在则报错】
a, 追加模式【可读; 不存在则创建;存在则只追加内容】
"+" 表示可以同时读写某个文件
r+, 读写【可读,可写】
w+,写读【可读,可写】
x+ ,写读【可读,可写】
a+, 写读【可读,可写】
"b"表示以字节的方式操作
rb 或 r+b
wb 或 w+b
xb 或 w+b
ab 或 a+b
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码
- 文件内置函数flush
flush原理:
- 文件操作是通过软件将文件从硬盘读到内存
- 写入文件的操作也都是存入内存缓冲区buffer(内存速度快于硬盘,如果写入文件的数据都从内存刷到硬盘,内存与硬盘的速度延迟会被无限放大,效率变低,所以要刷到硬盘的数据我们统一往内存的一小块空间即buffer中放,一段时间后操作系统会将buffer中数据一次性刷到硬盘)
- flush即,强制将写入的数据刷到硬盘
滚动条:
import sys,time
for i in range(10):
sys.stdout.write('#')
sys.stdout.flush()
time.sleep(0.2)
open函数详解
1. open()语法 open(file[, mode[, buffering[, encoding[, errors[, newline[, closefd=True]]]]]])
open函数有很多的参数,常用的是file,mode和encoding
file文件位置,需要加引号
mode文件打开模式,见下面3
buffering的可取值有0,1,>1三个,0代表buffer关闭(只适用于二进制模式),1代表line buffer(只适用于文本模式),>1表示初始化的buffer大小; encoding表示的是返回的数据采用何种编码,一般采用utf8或者gbk;
errors的取值一般有strict,ignore,当取strict的时候,字符编码出现问题的时候,会报错,当取ignore的时候,编码出现问题,程序会忽略而过,继续执行下面的程序。 newline可以取的值有None, , , ”, ‘ ',用于区分换行符,但是这个参数只对文本模式有效;
closefd的取值,是与传入的文件参数有关,默认情况下为True,传入的file参数为文件的文件名,取值为False的时候,file只能是文件描述符,什么是文件描述符,就是一个非负整数,在Unix内核的系统中,打开一个文件,便会返回一个文件描述符。
2. Python中file()与open()区别 两者都能够打开文件,对文件进行操作,也具有相似的用法和参数,但是,这两种文件打开方式有本质的区别,file为文件类,用file()来打开文件,相当于这是在构造文件类,而用open()打开文件,是用python的内建函数来操作,建议使用open
3. 参数mode的基本取值
Character | Meaning |
‘r' | open for reading (default) |
‘w' | open for writing, truncating the file first |
‘a' | open for writing, appending to the end of the file if it exists |
‘b' | binary mode |
‘t' | text mode (default) |
‘+' | open a disk file for updating (reading and writing) |
‘U' | universal newline mode (for backwards compatibility; should not be used in new code) |
r、w、a为打开文件的基本模式,对应着只读、只写、追加模式; b、t、+、U这四个字符,与以上的文件打开模式组合使用,二进制模式,文本模式,读写模式、通用换行符,根据实际情况组合使用、
常见的mode取值组合
1 r或rt 默认模式,文本模式读
2 rb 二进制文件
3
4 w或wt 文本模式写,打开前文件存储被清空
5 wb 二进制写,文件存储同样被清空
6
7 a 追加模式,只能写在文件末尾
8 a+ 可读写模式,写只能写在文件末尾
9
10 w+ 可读写,与a+的区别是要清空文件内容
11 r+ 可读写,与a+的区别是可以写到文件任何位置
- with用法
with open('a.txt','w') as f:
- 修改文件
import os
with open('a.txt','r',encoding='utf-8') as read_f,
open('.a.txt.swap','w',encoding='utf-8') as write_f:
for line in read_f:
if line.startswith('hello'):
line='哈哈哈
'
write_f.write(line)
os.remove('a.txt')
os.rename('.a.txt.swap','a.txt')
- 作业
编写数据库,基于文件实现增删改查功能
1 #!/usr/bin/python 2 # -*- coding:utf-8 -*- 3 4 5 def user_input(): # SQL语句输入入口 6 sql_count = 0 7 sql_text = input("SQL>") 8 if sql_text == 'exit': 9 return "exit" 10 elif sql_text == "": 11 return "continue" 12 while sql_text.endswith(';') != 1: # 实现换行输入, ";"作为结束符 13 sql_count += 1 14 sql_user = input("%s>" % sql_count) 15 sql_text = sql_text + " " + sql_user 16 sql_text = sql_text.split(";") # 去除";"号 17 sql_text = sql_text[0] 18 sql_text = sql_text.upper() # 全部转换为大写格式 19 sql_text = sql_text.split(" ") # 以空格为分割符,生成列表 20 while '' in sql_text: 21 sql_text.remove('') # 去除多余的空元素 22 return sql_text 23 24 25 def sql_analysis(sql_user_list): 26 sql_cut = sql_user_list[0] 27 if sql_cut == "SELECT": 28 sql_user_dict = sql_select_analysis(sql_user_list) 29 elif sql_cut == "INSERT": 30 sql_user_dict = sql_insert_analysis(sql_user_list) 31 elif sql_cut == "UPDATE": 32 sql_user_dict = sql_update_analysis(sql_user_list) 33 elif sql_cut == "DELETE": 34 sql_user_dict = sql_delete_analysis(sql_user_list) 35 else: 36 sql_user_dict = "err" 37 return sql_user_dict 38 39 40 def sql_select_analysis(sql_user_list): 41 sql_user_dict = { 42 'func': "select", 43 'SELECT': [], 44 'FROM': [], 45 'WHERE': [], 46 'LIMIT': [] 47 } 48 key = "SELECT" 49 for item in sql_user_list: 50 if item in sql_user_dict.keys(): 51 key = item 52 continue 53 if item not in sql_user_dict.keys(): 54 sql_user_dict[key].append(item) 55 if sql_user_dict.get('WHERE'): 56 sql_user_dict['WHERE'] = sql_where_analysis(sql_user_dict.get('WHERE')) 57 return sql_user_dict 58 59 60 def sql_insert_analysis(sql_user_list): 61 sql_user_dict = { 62 'func': "insert", 63 'INSERT': [], 64 'INTO': [], 65 'VALUES': [] 66 } 67 key = "INSERT" 68 for item in sql_user_list: 69 if item in sql_user_dict.keys(): 70 key = item 71 continue 72 if item not in sql_user_dict.keys(): 73 sql_user_dict[key].append(item) 74 return sql_user_dict 75 76 77 def sql_update_analysis(sql_user_list): 78 sql_user_dict = { 79 'func': "update", 80 'UPDATE': [], 81 'SET': [], 82 'WHERE': [] 83 } 84 key = "UPDATE" 85 for item in sql_user_list: 86 if item in sql_user_dict.keys(): 87 key = item 88 continue 89 if item not in sql_user_dict.keys(): 90 sql_user_dict[key].append(item) 91 if sql_user_dict.get('WHERE'): 92 sql_user_dict['WHERE'] = sql_where_analysis(sql_user_dict.get('WHERE')) 93 return sql_user_dict 94 95 96 def sql_delete_analysis(sql_user_list): 97 sql_user_dict = { 98 'func': "delete", 99 'DELETE': [], 100 'FROM': [], 101 'WHERE': [], 102 } 103 key = "DELETE" 104 for item in sql_user_list: 105 if item in sql_user_dict.keys(): 106 key = item 107 continue 108 if item not in sql_user_dict.keys(): 109 sql_user_dict[key].append(item) 110 if sql_user_dict.get('WHERE'): 111 sql_user_dict['WHERE'] = sql_where_analysis(sql_user_dict.get('WHERE')) 112 return sql_user_dict 113 114 115 def sql_where_analysis(sql_where_list): 116 where_key = ['AND', 'OR', 'NOT'] 117 where_char = "" 118 where_list = [] 119 for item in sql_where_list: 120 if item not in where_key: 121 where_char += item 122 continue 123 if item in where_key: 124 where_char = sql_where_analysis_second(where_char) 125 where_list.append(where_char) 126 where_list.append(item) 127 where_char = "" 128 else: 129 where_char = sql_where_analysis_second(where_char) 130 where_list.append(where_char) 131 return where_list 132 133 134 def sql_where_analysis_second(where_char): 135 key = ['>', '<', '='] 136 res = [] 137 char = '' 138 opt = '' 139 tag = False 140 for i in where_char: 141 if i in key: 142 tag = True 143 if len(char) != 0: 144 res.append(char) 145 char = '' 146 opt += i # opt='<=' 147 if not tag: 148 char += i # char='10' 149 if tag and i not in key: 150 tag = False 151 res.append(opt) 152 opt = '' 153 char += i # char='1' 154 else: 155 res.append(char) 156 if len(res) == 1: 157 res = list(res[0].partition('LIKE')) 158 return res 159 160 161 def sql_manage(sql_user_dict): 162 if sql_user_dict["func"] == "select": 163 if sql_user_dict['FROM']: 164 db_txt = sql_from_manage(sql_user_dict['FROM']) 165 if db_txt == "err": 166 return "err01" 167 else: 168 return "err01" 169 if sql_user_dict['WHERE']: 170 db_txt = sql_where_manage(sql_user_dict['WHERE'], db_txt) 171 if sql_user_dict['LIMIT']: 172 db_txt = sql_limit_manage(sql_user_dict['LIMIT'], db_txt) 173 if db_txt == "err": 174 return "err02" 175 if sql_user_dict['SELECT']: 176 db_txt = sql_select_manage(sql_user_dict['SELECT'], db_txt) 177 if db_txt == "err": 178 return "err02" 179 else: 180 return "err02" 181 return db_txt 182 elif sql_user_dict["func"] == "update": 183 if sql_user_dict['UPDATE']: 184 db_txt = sql_from_manage(sql_user_dict['UPDATE']) 185 if db_txt == "err": 186 return "err01" 187 else: 188 return "err01" 189 if sql_user_dict['WHERE']: 190 db_txt = sql_where_manage(sql_user_dict['WHERE'], db_txt) 191 if sql_user_dict['SET']: 192 db_txt = sql_set_manage(sql_user_dict['SET'], sql_user_dict['UPDATE'], db_txt) 193 if db_txt == "err": 194 return "err02" 195 else: 196 return "err02" 197 return db_txt 198 elif sql_user_dict["func"] == "insert": 199 if sql_user_dict['VALUES']: 200 db_txt = sql_values_manage(sql_user_dict['VALUES']) 201 if db_txt == 'err': 202 return "err02" 203 else: 204 return "err02" 205 if sql_user_dict['INTO']: 206 db_txt = sql_into_manage(sql_user_dict['INTO'], db_txt) 207 if db_txt == 'err': 208 return "err01" 209 else: 210 return "err01" 211 return db_txt 212 elif sql_user_dict["func"] == "delete": 213 if sql_user_dict['FROM']: 214 db_txt = sql_from_manage(sql_user_dict['FROM']) 215 all_db = db_txt 216 if db_txt == "err": 217 return "err01" 218 else: 219 return "err01" 220 if sql_user_dict['WHERE']: 221 db_txt = sql_where_manage(sql_user_dict['WHERE'], db_txt) 222 if not sql_user_dict['DELETE']: 223 db_txt = sql_delete_manage(all_db, db_txt, sql_user_dict['FROM']) 224 return db_txt 225 else: 226 return "err02" 227 228 229 def sql_select_manage(select_txt, db_txt): 230 if select_txt[0] == "*": 231 return db_txt 232 else: 233 user_txt = select_txt[0].split(",") 234 temp = ['ID', 'NAME', 'AGE', 'PHONE', 'DEPT', 'DATE'] 235 for key in user_txt: 236 if key not in temp: 237 return "err" 238 user_dict = {} 239 user_list = [] 240 for item in db_txt: 241 for user_key, user_value in item.items(): 242 if user_key in user_txt: 243 user_dict.setdefault(user_key, user_value) 244 user_list.append(user_dict) 245 user_dict = {} 246 return user_list 247 248 249 def sql_from_manage(from_list): 250 from_txt = from_list[0] 251 from_txt = from_txt.translate(str.maketrans('.', '/')) 252 import os 253 if os.path.exists(from_txt): 254 f1 = open(from_txt, 'r', encoding='utf-8') 255 content = f1.read() 256 f1.close() 257 user_attr_list = [] 258 db_str_list = content.split(' ') 259 for item in db_str_list: 260 temp = item.split('|') 261 v = { 262 'ID': temp[0], 263 'NAME': temp[1], 264 'AGE': temp[2], 265 'PHONE': temp[3], 266 'DEPT': temp[4], 267 'DATE': temp[5] 268 } 269 user_attr_list.append(v) 270 return user_attr_list 271 else: 272 return "err" 273 274 275 def sql_where_manage(where_list, db_text): 276 user_list = [] 277 for db_txt in db_text: 278 res = [] 279 for exp in where_list: 280 if type(exp) is list: 281 exp_k, opt, exp_v = exp 282 if exp[1] == '=': 283 opt = "%s=" % exp[1] 284 if db_txt[exp_k].isdigit(): 285 dic_v = int(db_txt[exp_k]) 286 exp_v = int(exp_v) 287 else: 288 dic_v = "'%s'" % db_txt[exp_k] 289 if opt != 'LIKE': 290 exp = str(eval("%s%s%s" % (dic_v, opt, exp_v))) 291 else: 292 if exp_v in dic_v: 293 exp = 'True' 294 else: 295 exp = 'False' 296 res.append(exp) 297 key = ['AND', 'OR', 'NOT'] 298 for item in res: 299 if item in key: 300 res[res.index(item)] = item.lower() 301 res = eval(' '.join(res)) 302 if res: 303 user_list.append(db_txt) 304 return user_list 305 306 307 def sql_limit_manage(limit_list, db_txt): 308 i = 0 309 user_list = [] 310 if limit_list[0].isdigit(): 311 limit_int = int(limit_list[0]) 312 else: 313 return "err" 314 for item in db_txt: 315 if i < limit_int: 316 user_list.append(item) 317 i += 1 318 else: 319 break 320 return user_list 321 322 323 def sql_set_manage(set_list, file_list, db_txt): 324 all_txt = sql_from_manage(file_list) 325 sql_delete_manage(all_txt, db_txt, file_list) 326 set_str = "".join(set_list) 327 set_list = [] 328 set_txt = "" 329 user_list = [] 330 for i in set_str: 331 if i == ',': 332 if set_txt != "": 333 set_list.append(set_txt) 334 user_list.append(set_list) 335 set_list = [] 336 set_txt = "" 337 continue 338 if i == '=': 339 if set_txt != "": 340 set_list.append(set_txt) 341 set_list.append(i) 342 set_txt = "" 343 else: 344 set_txt += i 345 else: 346 if set_txt != "": 347 set_list.append(set_txt) 348 if set_list: 349 user_list.append(set_list) 350 for item in user_list: 351 if len(item) != 3: 352 return "err" 353 exp_k, opt, exp_v = item 354 for n in db_txt: 355 if exp_k not in n.keys(): 356 return "err" 357 n[exp_k] = exp_v 358 db_str_list = [] 359 for item in db_txt: 360 temp = "%s|%s|%s|%s|%s|%s" % (item['ID'], item['NAME'], item['AGE'], item['PHONE'], item['DEPT'], item['DATE']) 361 db_str_list.append(temp) 362 for i in db_str_list: 363 sql_into_manage(file_list, i) 364 return_txt = "已修改%d行" % (len(db_txt)) 365 return_list = [return_txt] 366 return return_list 367 368 369 def sql_into_manage(from_list, db_txt): 370 from_txt = from_list[0] 371 from_txt = from_txt.translate(str.maketrans('.', '/')) 372 import os 373 if os.path.exists(from_txt): 374 f1 = open(from_txt, 'a', encoding='utf-8') 375 db_txt = " %s" % (db_txt,) 376 f1.write(db_txt) 377 f1.close() 378 return ['添加完成!'] 379 else: 380 return "err" 381 382 383 def sql_values_manage(user_list): 384 values_txt = user_list[0] 385 db_txt = "" 386 for i in values_txt: 387 if i in ['(', ')']: 388 continue 389 db_txt += i 390 db_txt = db_txt.split(",") 391 if len(db_txt) != 6: 392 return "err" 393 n = "|" 394 db_txt = n.join(db_txt) 395 return db_txt 396 397 398 def sql_delete_manage(all_list, user_list, file_name): 399 for line in user_list: 400 all_list.remove(line) 401 db_str_list = [] 402 for item in all_list: 403 temp = "%s|%s|%s|%s|%s|%s" % (item['ID'], item['NAME'], item['AGE'], item['PHONE'], item['DEPT'], item['DATE']) 404 db_str_list.append(temp) 405 db = " ".join(db_str_list) 406 file_name = file_name[0] 407 file_name = file_name.translate(str.maketrans('.', '/')) 408 f1 = open(file_name, 'w', encoding="utf-8") 409 f1.write(db) 410 f1.close() 411 return ['已删除!'] 412 413 414 def sql_main(): 415 while True: 416 sql_txt = user_input() 417 if sql_txt == 'exit': 418 break 419 elif sql_txt == 'continue': 420 continue 421 sql_txt = sql_analysis(sql_txt) 422 if sql_txt == "err": 423 print("语法错误!") 424 continue 425 sql_txt = sql_manage(sql_txt) 426 if sql_txt == "err01": 427 print("查询表不存在或为空!") 428 continue 429 elif sql_txt == "err02": 430 print("语法有误!") 431 continue 432 for line in sql_txt: 433 print(line) 434 435 if __name__ == '__main__': 436 sql_main()