Python編碼/文件讀取/多線程
個人筆記~~記錄才有成長 編碼/文件讀取/多線程
編碼
常用的一般是gbk、utf-8,而在python中字符串一般是用Unicode來操作,這樣才能按照單個字來處理,所以需要對不同的編碼格式進行轉化。
這里需要的函數decode和encode,形式都很簡單,只要牢記對應的格式對應的編碼就好
如果是utf-8,想轉換成unicode content.decode('utf-8') 如果是Utf-8,想轉換成gbk content.decode('utf-8').encode('gbk')
注意:對於Python可以在.py中指定編碼格式,如下選擇的是utf-8格式
# -*- coding: utf-8 -*-
文件讀取
傳統的讀法,全部讀出,按行處理:
fp=open("./output.txt", "r"); alllines=fp.readlines(); fp.close(); for eachline in alllines: print eachline;
使用文件迭代器 , 每次只讀取和顯示一行:
fp=open("./output.txt", "r"); for eachline in fp: print eachline;
讀取和保存CSV文件,使用CSV模塊
import csv def loadFile(file_name): f = open(file_name) r = csv.reader(f) for item in r: print item type = sys.getfilesystemencoding() for line in r: def saveFile(result): writer = csv.writer(open('result.csv','w'), dialect='excel') for item in result: writer.writerow(item)
多線程
由於程序數據有點大,嘗試一下Python的多線程,其實和C++/JAVA都是類似的
調用thread模塊中的start_new_thread()函數來產生新線
import time import thread def timer(n, ID): cnt = 0 while cnt<n: print 'Thread:(%d) Time:%s\n'%(ID,time.ctime()) cnt+=1 thread.exit_thread() def test(): #Use thread.start_new_thread() to create 2 new threads thread.start_new_thread(timer, (5,1)) thread.start_new_thread(timer, (5,2)) if __name__=='__main__': test()
python中的線程是通過thread模塊來調用的,調用thread.start_new_thread()函數,該函數由兩部分參數,第一個參數為線程函數,第二個參數為提供給線程函數的tuple型參數。
使用threading模塊的 Thread類
這里要接觸到繼承的概念了,這種處理方式相對來說要清晰的多。
通過調用threading模塊繼承threading.Thread類來包裝一個線程對象。
- 在自己的線程類的__init__里調用threading.Thread.__init__(self, name = threadname)
- Threadname為線程的名字
- run(),通常需要重寫,編寫代碼實現做需要的功能。
- getName(),獲得線程對象名稱
- setName(),設置線程對象名稱
- start(),啟動線程
- jion([timeout]),等待另一線程結束后再運行。
- setDaemon(bool),設置子線程是否隨主線程一起結束,必須在start()之前調用。默認為False。
- isDaemon(),判斷線程是否隨主線程一起結束。
- isAlive(),檢查線程是否在運行中。
import time import thread import threading def timer1(n, ID): cnt = 0 while cnt<n: print 'Thread:(%d) Time:%s\n'%(ID,time.ctime()) cnt+=1 thread.exit_thread() class timer2(threading.Thread): #The timer class is derived from the class threading.Thread def __init__(self, ID): threading.Thread.__init__(self) self.m_ID = ID self.m_stop = False def run(self): while not self.m_stop: time.sleep(2) print 'Thread Object(%d), Time:%s\n' %(self.m_ID, time.ctime()) def stop(self): self.m_stop = True def test(): #Use thread.start_new_thread() to create 2 new threads #thread.start_new_thread(timer1, (5,1)) #thread.start_new_thread(timer1, (5,2)) thread1 = timer2(1) thread2 = timer2(2) thread1.start() thread2.start() time.sleep(5) thread1.stop() thread2.stop() if __name__=='__main__': test()
![]()
本作品采用 知識共享署名-非商業性使用-相同方式共享 3.0 未本地化版本許可協議進行許可。歡迎轉載,請注明出處:
轉載自: cococo點點 http://www.cnblogs.com/coder2012