文件操作 / IO
os.walk() 和 os.path.walk()
一、os.walk()
函數聲明:os.walk(top,topdown=True,onerror=None)
(1)參數top表示需要遍歷的頂級目錄的路徑。
(2)參數topdown的默認值是“True”表示首先返回頂級目錄下的文件,然后再遍歷子目錄中的文件。當topdown的值為"False"時,表示先遍歷子目錄中的文件,然后再返回頂級目錄下的文件。
(3)參數onerror默認值為"None",表示忽略文件遍歷時的錯誤。如果不為空,則提供一個自定義函數提示錯誤信息后繼續遍歷或拋出異常中止遍歷。
返回值:函數返回一個元組,含有三個元素。這三個元素分別是:每次遍歷的路徑名、路徑下子目錄列表、目錄下文件列表。
二、os.path.walk
函數聲明:os.path.walk(top,func,arg)
(1)參數top表示需要遍歷的目錄路徑
(2)參數func表示回調函數,即對遍歷路徑進行處理的函數。所謂回調函數,是作為某個函數的參數使用,當某個時間觸發時,程序將調用定義好的回 調函數處理某個任務。注意:walk的回調函數必須提供三個參數:第1個參數為os.path.walk的參數arg,第2個參數表示目錄 dirname,第3個參數表示文件列表names。注意:os.path.walk的回調函數中的文件列表不和os.walk()那樣將子目錄和文件分 開,而是混為了一攤,需要在回調函數中判斷是文件還是子目錄。
(3)參數arg是傳遞給回調函數的元組,為回調函數提供處理參數,arg可以為空。回調函數的第1個參數就是用來接收這個傳入的元組的。
參考: http://my.oschina.net/duhaizhang/blog/68202
輸入
input 和 raw_input
input返回的是數值類型: int 或 float
raw_input返回的是string類型
例子
>>> s = input('請輸入:')請輸入:45 + 32>>> s77>>> type(s)<type 'int'>>>> s = raw_input('請輸入:')請輸入:45 + 32>>> s'45 + 32'>>> type(s)<type 'str'>
Python三目運算符的實現
條件 and 表達式1 or 表達式2
例子:
>>> 1 > 0 and 'yes' or 'no''yes'其他語言的寫法對比:1 > 0 ? 'yes' : 'no'
** 運算符 -- 相當于 power()函數
>>> 2 ** 1 # 2的一次方2>>> 2 ** 2 # 2的二次方4>>> 2 ** 3 # 2的三次方8
妙用 ** 運算符 開根號
# 開根號2
>>> 2 ** (1.0/2)
1.4142135623730951
>>> 4 ** (1.0/2)
2.0
# 開根號3
>>> 8 ** (1.0/3)
2.0
注: 1/3, 只保留整數位, 也就是 1/3的結果是0
Python中的 <> 相當于 !=, 不等于 -- 不建議使用
>>> 2 <> 1 # 2 不等于 1True
字符串
Python中, 單引號 雙引號 和 三單引號 三雙引號的區別
單引號 和 雙引號是一樣的, 括起來表示字符串
三單引號 和 三雙引號也是一樣的, 括起來會幫助我們自動換行, 對于有多個 '/n'的字符串, 會清晰易懂
>>> s = '''hello,... my... name... is... Juggling.'''>>> s'hello,/nmy/nname/nis/nJuggling.'>>> PRint shello,mynameisJuggling.
利用urllib2抓取網頁內容
>>> import urllib2>>> f = urllib2.open('http://fanyi.youdao.com/openapi.do?keyfrom=zqhong&key=694644553&type=data&doctype=json&version=1.1&q=good')>>> f = urllib2.urlopen('http://fanyi.youdao.com/openapi.do?keyfrom=zqhong&key=694644553&type=data&doctype=json&version=1.1&q=good')>>> json_str = f.read()
利用Pygame播放mp3
>>> import pygame.mixer as mixer>>> mixer.init()>>> mixer.music.load('na.mp3')>>> mixer.music.play()--------------------------------------------------------方法介紹:pygame.init() 進行全部模塊的初始化,pygame.mixer.init() 或者只初始化音頻部分pygame.mixer.music.load('xx.mp3') 使用文件名作為參數載入音樂 ,音樂可以是ogg、mp3等格式。載入的音樂不會全部放到內容中,而是以流的形式播放的,即在播放的時候才會一點點從文件中讀取。pygame.mixer.music.play()播放載入的音樂。該函數立即返回,音樂播放在后臺進行。play方法還可以使用兩個參數pygame.mixer.music.play(loops=0, start=0.0) loops和start分別代表重復的次數和開始播放的位置。pygame.mixer.music.stop() 停止播放,pygame.mixer.music.pause() 暫停播放。pygame.mixer.music.unpause() 取消暫停。pygame.mixer.music.fadeout(time) 用來進行淡出,在time毫秒的時間內音量由初始值漸變為0,最后停止播放。pygame.mixer.music.set_volume(value) 來設置播放的音量,音量value的范圍為0.0到1.0。pygame.mixer.music.get_busy() 判斷是否在播放音樂,返回1為正在播放。pygame.mixer.music.set_endevent(pygame.USEREVENT + 1) 在音樂播放完成時,用事件的方式通知用戶程序,設置當音樂播放完成時發送pygame.USEREVENT+1事件給用戶程序。 pygame.mixer.music.queue(filename) 使用指定下一個要播放的音樂文件,當前的音樂播放完成后自動開始播放指定的下一個。一次只能指定一個等待播放的音樂文件。--------------------------------------------------------
關于id()方法
>>> i1 = 10>>> i2 = 10>>> id(i1)28790912>>> id(i2)28790912>>> f1 = 1.5>>> f2 = 1.5>>> id(f1)28862112>>> id(f2)28862160id()方法可以得到對象在內存中的位置, 類似于"指針"Python默認會緩沖Integer, 但是Float不會. 從上面可以看出
關于.py, .pyc, .pyo文件
py是源程序pyc是編譯后的程序 在執行python源程序時,python會自動將源程序編譯成為pyc文件pyo是優化編譯后的程序 python -O 源文件即可將源程序編譯為pyo文件 如何將py編譯成pyc?1. 只編譯一個py文件import py_compilepy_compile.compile(r'H:/game/test.py')2. 對一個文件夾的所有py文件進行編譯import compileallcompileall.compile_dir(dirpath)如何將py編譯優化成pyo?python -O -m py_compile file.py
關于3 < 4 < 5
3 < 4 < 5 ==> 相當于 3 < 4 and 4 < 5>>> 3 < 4 < 5True>>> 3 < 4 and 4 < 5True
xml to JSON
import xmltodict, jsono = xmltodict.parse('<a>text</a>')json.dumps(o)
pip -- A tool for installing and managing Python packages.
pip 是管理Python包的工具. 類似于 easy_install1. 安裝pip$ wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py$ python get-pip.py2. pip的使用# 安裝第三方包$ pip install simplejson# 升級第三方包$ pip install --upgrade simplejson# 卸載第三方包$ pip uninstall simplejson
Python按行讀取文件,如何去掉'/n'
for line in file.readlines(): line=line.strip('/n')
range()的用法 和 切片的用法差不多
# 從0開始, 不包括10>>> range(10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]# 從5開始, 不包括10>>> range(5, 10)[5, 6, 7, 8, 9]# 從0開始, 不包括10, 步長為3>>> range(0, 10, 3)[0, 3, 6, 9]# 從-10開始, 不包括-100, 步長為-30 >>> range(-10, -100, -30)[-10, -40, -70]>>> range(10, 0, -1)[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
linux中使用Python模擬鍵盤按鍵
這里以 ctrl + shifit + v為例子 (我的系統中, ctrl + shift + v為粘貼)
#!/usr/bin/env python#-*- coding: utf-8 -*-import virtkeyv = virtkey.virtkey()# press按下v.press_keycode(37) # ctrlv.press_keycode(50) # shiftv.press_unicode(ord('v')) # v# 釋放按鍵v.release_unicode(ord('v'))v.release_keycode(50)v.release_keycode(37)
這樣就有一個問題, 如何獲取 keycode?
方法1:$ showkey -k注: 這個方法獲取的keycode需要 加8方法2:$ xve方法3:dmesg注: 如果是特殊的keycode, 可以通過這個方法方法4:xmodmap -pke
執行系統命令和sleep
import osos.system('commond')example:os.system('ls') #執行ls命令import timetime.sleep(1) # 暫停1秒
Python中各進制的轉換
首先, Python中二進制, 八進制, 十六進制的表示
# 二進制>>> 0b102# 八進制>>> 0108# 十六進制>>> 0x1016
各進制的轉換
#十進制轉換二進制 >>> bin(10) '0b1010' #十進制轉換十六進制 >>> hex(10) '0xa' #二進制轉換十進制 >>> int('1010',2) 10 #十六進制轉換十進制 >>> int('0xa',16) 10 #十六進制轉換二進制 >>> bin(0xa) '0b1010' #二進制轉換十六進制 >>> hex(0b1010) '0xa'
Python中, 對時間的處理
http://blog.csdn.net/xiaobing_blog/article/details/12591917
# 1. 時間戳轉字符串 --> 獲取當前的時間戳, 并格式化成特定的字符串>>> import time>>> now = int(time.time())>>> timeArray = time.localtime(now)>>> timeArraytime.struct_time(tm_year=2014, tm_mon=8, tm_mday=25, tm_hour=16, tm_min=28, tm_sec=30, tm_wday=0, tm_yday=237, tm_isdst=0)>>> time.strftime('%Y-%m-%d %H:%M:%S', timeArray)'2014-08-25 16:28:30'# 2. 將字符串轉時間戳>>> a = '2013-10-10 23:40:00'>>> timeArray = time.strptime(a, '%Y-%m-%d %H:%M:%S')>>> timeStamp = int(time.mktime(timeArray))>>> timeStamp1381419600
某年某月某日是星期幾
>>> import datetime>>> todate = datetime.datetime(2014, 9, 1)>>> todatedatetime.datetime(2014, 9, 1, 0, 0)>>> todate.weekday() + 11為什么需要加1, 查看文檔weekday(...) Return the day of the week represented by the date. Monday == 0 ... Sunday == 6
命令行解析工具 getopt()的使用
預備知識:
文件: get.py內容:#!/usr/bin/python#-*- coding: utf-8 -*-for arg in sys.args: print arg調用get.pypython get.py -o 123.txt --help file1 file2 結果:get.py-o123.txt--helpfile1file2注: argv[0] --> 我們python腳本的名字 后面才是我們帶的參數
實例分析:
import sys, getopttry: opts, args = getopt.getopt(sys.argv[1:], 'ho:', ['help', 'output='])except getopt.GetoptError as err: print str(err) sys.exit(2)for o, a in opts: if o in ('-h', '--help'): print o, a sys.exit() if o in ('-o', '--output'): print o, a解釋: 1. sys.argv[1:], 過濾掉第一個參數(因為它是執行腳本的名字, 不應算參數的一部分) 2. 短格式分析串'ho:', 其中, 'h'是開關選項, 不帶參數, 'o:'則表示改選項后面帶一個參數, 舉例: python example.py -h -o 123.txt 3. 長格式分析串列表: ['help', 'output=']. 同理, 'help'是開關選項, 不帶參數, 'output='后面帶參數. (后面有‘=’表示要帶參數) 分析: '-h -o file --help --output=out.txt file1 file2' 分析后, opts為: [('-h', ''), ('-o', 'file'), ('--help', ''), ('--output', 'out.txt')] args則為: ['file1', 'file2']
httplib2的使用
# 1. 獲取httpli2.Http對象import httplib2h = httplib2.Http()Http這個class的 初始化方法 __init__:__init__(self, cache=None, timeout=None, proxy_info=<function proxy_info_from_environment>, ca_certs=None, disable_ssl_certificate_validation=False)注:h = httplib2.Http('.cache')這個意思是: 講緩沖保存在當前目錄下的 '.cache'目錄# 2. 例子 -- To PUT some content to a server that uses SSL and Basic authentication 注: method都需要大寫, 比如"GET", "PUT"#!/usr/bin/env python#-*- coding: utf-8 -*-import httplib2h = httplib2.Http('.cache')h.add_credentials('name', 'passWord')(resp, content) = h.request('https://example.org/chapter/2', 'PUT', body='This is text', headers={'content-type': 'text/html'})# 例子import httplib2h = httplib2.Http('.cache')(resp, content) = h.request('http://bitworking.org/', 'GET')(resp, content) = h.request('http://bitworking.org/', headers={'cache-control': 'no-cache'})附錄: | request(self, uri, method='GET', body=None, headers=None, redirections=5, connection_type=None) | Performs a single HTTP request. | | The 'uri' is the URI of the HTTP resource and can begin with either | 'http' or 'https'. The value of 'uri' must be an absolute URI. | | The 'method' is the HTTP method to perform, such as GET, POST, DELETE, | etc. There is no restriction on the methods allowed. | | The 'body' is the entity body to be sent with the request. It is a | string object.
注: httplib2返回的 resp 和 content 分別是 response 和 content, 其中, response是字典, 可以很方便的得到結果, 比如 resp['status'] , 得到狀態碼
Python自動補齊
https://github.com/itnihao/vimrc-python
注: 快捷鍵修改成 ctrl + n
編輯 /home/akira/.vim/bundle/pydiction/after/ftplugin/python_pydiction.vim
找到 inoremap <silent> <buffer> <Tab>
修改成: inoremap <silent> <buffer> <C-n>
import os
os.path.isfile('test.txt') #如果不存在就返回False
os.path.exists(directory) #如果目錄不存在就返回False
Python中執行系統命令的三種方法
# 第一種 system(command) -> exit_status 返回的是exit_status>>> import os>>> status = os.system('ls')>>> status0# 第二種 os.popen(command [, mode='r' [, bufsize]]) -> pipe Open a pipe to/from a command returning a file object.>>> import os>>> result = os.popen('df -h')>>> result.read()'Filesystem Size Used Avail Use% Mounted on/n/dev/sda1 # 第三種 commands - Execute shell commands via os.popen() and return status, output.getoutput(cmd) Return output (stdout or stderr) of executing cmd in a shell. getstatus(file) Return output of "ls -ld <file>" in a string. getstatusoutput(cmd) Return (status, output) of executing cmd in a shell.>>> import commands>>> commands.getstatusoutput('ls /home/akira/Documents')(0, 'mykeycode/nsearch_keyword.py/ntest.py')>>> commands.getoutput('ls /home/akira/Documents')'mykeycode/nsearch_keyword.py/ntest.py'>>> commands.getstatus('/home/akira/Documents/mykeycode')'-rw-r--r-- 1 akira akira 12945 Aug 24 13:32 /home/akira/Documents/mykeycode'
Python中的 chr(), ord(), unichr()
# int轉char 例子: chr(65) --> 'A'
chr(...) chr(i) -> character Return a string of one character with ordinal i; 0 <= i < 256.
# char轉int 例子: ord('A') --> 65ord(...) ord(c) -> integer Return the integer ordinal of a one-character string.# int轉unicode 例子: unichr(65) --> u'A'unichr(...) unichr(i) -> Unicode character Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
Python中如何查看內置函數
import __builtin__help(__builtin__)
Python中如何不換行輸出 --> 看內置函數print()的參數
print(...) print(value, ..., sep=' ', end='/n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.注: 需要python3.x支持# file 默認print輸出到標準輸出流屏幕, 不過這個是可以更改的 注:需要close()這個 file-like object 不然 默認系統會先寫入緩沖 到緩沖一定大小才會輸出>>> fw = open('./hhh', 'w')>>> print('hello world!', file=fw)>>> fw.close()# sep 兩個value中間用什么分隔。 默認是 space>>> print('hello','world', sep='1')hello1world# end 默認, 輸出的時候以'/n'結尾, 但是有的時候, 我們不需要, 則可以用 end=''替換>>> print('hello', end='')hello>>> # flush, 當flush為True時, 強制每次寫入數據時都刷新一次# 注: 我們不需要close fw就可以看到我們寫入的數據了>>> fw = open('ggg', 'w')>>> print('jjj', file=fw, flush=True)
Python如何查詢函數, 和其他幫助信息
# 1. 打印關鍵字>>> help()help> keywordsHere is a list of the Python keywords. Enter any keyword to get more help.and elif if print....del global pass # 2. 查看相關話題 這里以NONE為例子help> topicshelp> NONE# 3. 查詢所有可用模塊help> modulesPlease wait a moment while I gather a list of all available modules...ANSI _random gdbm quopriBaseHTTPServer _sha genericpath randomBastion _sha256 getopt re...._multiprocessing functools pylint zope_osx_support future_builtins pynotify _pyio gc pyquery # 4. 使用dir, 查看對象有什么屬性>>> dir('a')['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
# 5. 查看當前作用域的名稱
>>> dir()
['GFileDescriptorBased', 'GInitiallyUnowned', 'GPollableInputStream', 'GPollableOutputStream', 'GstChildProxy', 'GstProxyPad', 'Person', '__builtins__', '__doc__', '__name__', '__package__', 'a', 'bob', 'f', 'info', 'joe', 'keyword', 'p', 'str', 'sys']
sys模塊的常用方法
# 1. sys.argv 傳入參數 argv[0]為Python腳本名# 2. sys.path 模塊搜索路徑 path[0]為當前腳本目錄 修改的話 可以在 ~/.zshrc 或者 ~/.profile 中添加 export PYTHONPATH=/home/akira/Documents/Python/# 3. 查看平臺>>> sys.platform'linux2'# 4. 查看Python版本>>> sys.version'2.7.6 (default, Mar 22 2014, 22:59:56) /n[GCC 4.8.2]'>>> sys.version_infosys.version_info(major=2, minor=7, micro=6, releaselevel='final', serial=0)# 5. 查看最大整數>>> sys.maxint9223372036854775807
re模塊
關于flags參數
解釋
Some of the functions in this module takes flags as optional parameters: I IGNORECASE Perform case-insensitive matching. L LOCALE Make /w, /W, /b, /B, dependent on the current locale. M MULTILINE "^" matches the beginning of lines (after a newline) as well as the string. "$" matches the end of lines (before a newline) as well as the end of the string. S DOTALL "." matches any character at all, including the newline. X VERBOSE Ignore whitespace and comments for nicer looking RE's. U UNICODE Make /w, /W, /b, /B, dependent on the Unicode locale. This module also defines an exception 'error'.使用:>>> import re>>> re.IGNORECASE (常數)
例子:
# re.IGNORECASE 忽略大小寫>>> re.findall('[a-z]', 'abcABCtT', flags=re.IGNORECASE)['a', 'b', 'c', 'A', 'B', 'C', 't', 'T']
在Python中使用ping
https://pypi.python.org/pypi/ping/0.2pip install ping
方法介紹:
FUNCTIONS checksum(source_string) I'm not too confident that this is right but testing seems to suggest that it gives the same answers as in_cksum in ping.c do_one(dest_addr, timeout, psize) Returns either the delay (in seconds) or none on timeout. quiet_ping(dest_addr, timeout=2, count=4, psize=64) Send `count' ping with `psize' size to `dest_addr' with the given `timeout' and display the result. Returns `percent' lost packages, `max' round trip time and `avrg' round trip time. receive_one_ping(my_socket, id, timeout) Receive the ping from the socket. send_one_ping(my_socket, dest_addr, id, psize) Send one ping to the given >dest_addr<. verbose_ping(dest_addr, timeout=2, count=4, psize=64) Send `count' ping with `psize' size to `dest_addr' with the given `timeout' and display the result.
常用方法:
quiet_ping(dest_addr, timeout=2, count=4, psize=64)
返回值:
>>> ping.quiet_ping('127.0.0.1')
(0, 0.15997886657714844, 0.1087188720703125)
第一個數字'0': 丟失的包的個數; 第二個數字'0.15997886657714844': 最大使用使用; 第三個數字'0.1087188720703125': 平均使用時間
# ping一個不存在的地址 結果 max_time = None, avg_time = None
>>> ping.quiet_ping('1.1.1.1')
(100, None, None)
verbose_ping(dest_addr, timeout-3, count-4, psize=64)
>>> ping.verbose_ping('127.0.0.1')
ping 127.0.0.1 with ... get ping in 0.1800ms
ping 127.0.0.1 with ... get ping in 0.0880ms
ping 127.0.0.1 with ... get ping in 0.0839ms
ping 127.0.0.1 with ... get ping in 0.0830ms
 注: 使用這個ping模塊, 需要root的權限執行。 
 不然, 會拋出如下錯誤
 socket.error: Operation not permitted - Note that ICMP messages can only be sent from processes running as root.
 實例代碼, 測試一個網段存活的ip
https://gist.github.com/zqhong/85828f78b11995bde1d7
pdb調試技巧
q 退出debugh 打印可用的調試命令b 設置斷點,b 5 在第五行設置斷點h command 打印command的命令含義disable codenum 使某一行斷點失效enable codenum 使某一行的斷點有效condition codenum xxx 針對斷點設置條件c 繼續執行程序,直到下一個斷點n 執行下一行代碼,如果當前語句有函數調用,則不會進入函數體中s 執行下一行代碼,但是s會進入函數w 打印當前執行點的位置j codenum 讓程序跳轉到指定的行l 列出附近的源碼p 打印一個參數的值a 打印當前函數及參數的值回車 重復執行上一行
注: 這里使用的是 Python 2.7
新聞熱點
疑難解答