@nemos
2017-05-05T15:17:47.000000Z
字数 4398
阅读 805
py
import csvfrom collections import namedtuplewith open('xxx.csv') as f:f_csv = csv.reader(d) #读取为元组序列f_csv = csv.DictReader(f) #读取为字典序列headers = next(f_csv) #数据头Row = namedtuple('Row', headers) #从list中初始化命名元组类for r in f_csv: #读出每一行r[0] #元组下标索引索引row = Row(*r) #将元组解包用于初始化对象row.data #用data索引元素r['data'] #字典序列索引
headers = ['header1','header2']rows = [('x', 'x'), ('x', 'x')]with open('xxx.csv') as f:f_csv = csv.writer(f)f_csv.writerow(headers)f_csv.writerows(rows)
import jsondata={'xxx': 'xxx',}json_str = json.dumps(data) #字符串读取data = json.loads(json_str)with open('data.json', 'w') as f:json.dump(data, f) #写入文件with open('data.json', 'r') as f:data = json.load(f)
| mode参数 | 含义 |
|---|---|
r |
只读,默认 |
w |
写入,覆盖原文件 |
a |
若存在则追加 |
b |
二进制模式,可叠加 |
+ |
读写模式,可叠加 |
t |
以文本模式打开 |
fileobj = open(path[, mode[, buffering]]) #缓存-1参数使用默认大小None = f.write() #多次写入会追加None = f.close() #关闭文件流data = f.read([nbits]) #默认读取全部文件#读写都会移动光标None = f.seek(offset[, whence]) #移动光标到指定位置# offset表示偏移字节数负的从文件尾开始,whence表示起始位置默认为0data = f.readline([maxbit]) #读取行包括换行符,可指定最大字符数data = f.readlines() #将所有行作为列表返回None = f.writelines(iter) #写入多行
确保文件被正常关闭
with open('filepath') as somefile:do_something(somefile)
$ python script.py file1.txt file2.txt
fileinput.input([files[, inplace, backup]])#返回可遍历对象,每次遍历一行# inplace=True 原地处理,backup 备份路径fileinput.filename() #返回当前文件名称fileinput.lineno() #返回当前累计行数,多文件会持续fileinput.filelineno() #返回当前文件行数fileinput.isfirstline() #检查当前行是否为第一行fileinput.isstdin() #检查当前文件是否为stdinfileinput.nextfile() #关闭当前文件跳到下一个文件且跳过行数不计fileinput.close() #关闭整个文件链
urllib2增加了http验证和cookies
from urllib import urlopenwebpagefile = urlopen('http://www.python.org')
urllib.qoute(string[, safe]) #将传入的字符转化为url友好字符urllib.quote_plus... #功能相同,用+代替空格urllib.unquote(string) #跟quote功能相反urllib.unquote_plus(string)urllib.urlencode(query[, doseq])#将映射转化为字符
import sqlite3 as slconn = sl.connect('xxx.db') #连接数据库 不存在则创建cursor =conn.cursor() #返回游标对象cursor.execute('') #执行语句cursor.fetchall()cursor.rowcount #数据数目cursor.close()conn.commit()conn.close()
sys.argv #命令行参数# pyhthon file.py [arg]sys.exit([arg]) #退出当前程序且返回相应错误信息sys.modules #映射模块名称到载入模块的字典sys.path #import语句所查找的模块目录sys.platform #平台标识符sys.stdin,stdout,stderr #文件流
os.getcwd() #获得当前目录os.listdir() #返回目录下所有文件的listos.mkdir()os.rename('old', 'new')os.rmdir()os.path.abspath(file.txt) #返回文件的绝对路径os.path.split(file.txt) #将文件的路径以文件夹,文件的格式分离os.path.dirname(file.txt) #返回文件所在的文件夹os.path.basename(file.txt) #返回文件的全名os.path.splitext(file.txt) #分离文件的拓展名os.path.exists()os.path.isfile()os.path.isdir()os.path.expanduser('~/local') #返回以用户路径连接的路径名os.join() #连接路径os.environ #环境变量的字典os.getenv('PYTHONPATH') #获得环境变量os.system(command) #在shell中执行指定的命令os.sep #路径分割符# unix '/' windows '\\' macos ':'os.pathsep #分割路径的分隔符# unix ':' windows ';' macos '::'os.linesep #字符串分割符即行分割符# unix '\n' windows '\r\n' macos '\r'os.startfile #接受路径打开文件
(0,年) 如2016
(1,月) 1-12
(2,日) 1-31
(3,时) 0-23
(4,分) 0-59
(5,秒) 0-61
(6,周) 0-6
(7,儒历日) 1-366
(8,夏令时) 0,-1,1
strtime = time.asctime([timetuple]) #参数可选下同timetuple = time.localtime([secs]) #secs = time.mktime(timetuple) #与上函数功能相反None = time.sleep(secs) #休眠timetuple = time.strtime(string[, format]) #解析字符串为时间元组secs = time.time()
生成一个伪随机数
#系统相关强加密os.urandom() #返回一个random对象
obj = random.SystemRandom() #功能与os.urandom()类似num[0,1) = random.random()num = random.getrandbits(n) #以长整型的形式返回一个nbits的随机数num = randrange([start,] stop[, step]) #返回range()中的随机数ele = choice(seq) #返回序列中的随机元素None = shuffle(seq[, random]) #随机排列序列subseq = sample(seq, n) #从序列中返回n个随机且独立的元素
re.I(IGNORECASE): 忽略大小写re.M(MULTILINE): 多行模式,改变'^'和'$'的行为re.S(DOTALL): 点任意匹配模式,改变'.'的行为re.L(LOCALE): 使预定字符类 \w \W \b \B \s \S 取决于当前区域设定re.U(UNICODE): 使预定字符类 \w \W \b \B \s \S \d \D 取决于unicode定义的字符属性re.X(VERBOSE): 详细模式。这个模式下正则表达式可以是多行,忽略空白字符,并可以加入注释。
reboj = re.compile(pattern[, flags]) #根据正则表达式字符串创建模式对象MatchObject = re.search(pattern, string[, flags]) #任意位置,匹配一次MatchObject = re.match(pattern, string[, flags]) #匹配开头list = re.findall(pattern, string) #匹配全部list re.split(pattern, string[, maxsplit = 0]) #根据匹配模式来分割字符串str = re.sub(pat, repl, string[, count=0]) #将匹配到的字符用repl替换str = re.escape(string) #字符变为pat 不用转义
str = MatchObject.group([groupnum,...]) #获取指定组的匹配项num = MatchObject.start([groupnum]) #指定组的开始位置num = MatchObject.end([groupnum]) #同上tuplenum = MatchObject.span([groupnum]) #开始和结束的位置
模块即为python文件
导入即被执行
包包含多个模块
本质为一个文件夹
根目录下边包含init.py文件
导入时 init文件会被执行
#A包包含B模块import A #导入A包import A.B #从A包中导入B模块,但要以A.B来使用from A import B #功能与上语句相同,但可作为B来使用模块dir(pak)#可查看包内包含的内容mod.__all__ #定义模块公用接口from pak import * #__all__ 变量定义了import*可调用的方法mod.__doc__ #模块的文档mod.__file__ #模块所在的位置