2016年12月13日 星期二

[Django] 1.7.3 讀檔與寫入檔案

資料檔的讀寫是python 的基本功能之一

開啟檔案:使用open函數

fp = open('test_file.txt','r')
a = fp.read()
b = fp.readline()
c = fp.readlines()
fp.close()
其中,test_file的欄位可填入絕對路徑,但是請注意
windows: fp = open('C:\\Users\\jack\\Desktop\\test_file.txt')
mac : fp = open('/Users/Documents/test_file.txt')
因為windows的路徑的斜線是\,會造成跳脫字元,所以要輸入兩個\
而mac沒有這個困擾

r:讀檔 w:寫入 a:附加

讀取檔案的方法有三種:read(), readline(), readlines()
      read() : 一口氣讀完
 readline():一次只讀一行文字檔,傳回一個字串
readlines():把每一行拆開放在不同的字串變數,最後彙整成一個串列




f = open ('C:\\Users\\jack\\Desktop\\MP21602\\zop.txt','r')

print (f.read())

#f = open ('C:\\Users\\jack\\Desktop\\MP21602\\zop.txt','r')
print (f.readline())
print (f.readline())

f = open ('C:\\Users\\jack\\Desktop\\MP21602\\zop.txt','r')
print (f.readlines())
read() 會顯示全部內容
readline() 照理說會顯示
 >>>
Beautiful is better than ugly

 Explicit is better than implicit
>>>

 因為純文字格式每行後面都有個換行符號\n ,加上本身print也有一個換行
有兩種解決方法
(1) 用strip()清除字串頭尾非必要字元
(2) print      ,end=""

使用with敘述可以讓程式更簡潔

with open('C:\\Users\\jack\\Desktop\\MP21602\\zop.txt','r') as f:
     for line in f:
         print line

上述程式把要讀取的檔案名稱寫在程式碼並不是個很好的方式,通常會把要操作的文字對象已執行參數的方式輸入 程式命令列函數可以用sys.argv取得

import sys

if len(sys.argv)<2:
    print("How to use: python 8-2.py class")
    exit(1)

std_data = dict()

with open(sys.argv[1],encoding='utf-8') as fp:
    alldata = fp.readlines()

for line in alldata:
    no,name = line.rstrip('\n').split(',')
    std_data[no] = name

print (std_data)

<\pre>


[Django]1.7.2

break and continue

如果while的條件總是成立,我們稱其為無窮迴圈.
使用時機:當我們的程式需要等待使用者的一些要求時

while True:
print “never stop”

而break 跟 continue 則可以強制介入迴圈

n = 5

count = 1

while True:

print "just print {} times".format(count)

if count == n:



break

count+=1

continue 的用法

n = 1

while n<=10:

if n==5:

n+=1

continue

print n

n+=1

for 迴圈

lst = [1,2,3]
for num in lst:
print num

for item in lst:
suite
將lst中的元素一個個取出,每取出一個便將他賦值(代入)
並且執行一次suite

for 可以對清單 元組 字典 字串 進行迭代

使用時機
for :當重複的次數可以被計算時
while:當條件清楚時



comprehension

lst = [1,2,3,4,5]
lst_eq = [n**2 for n in lst]
lst_eq1=[n**2 for n in lst if n%2==0]

>>>lst_eq
[1,4,9,16,25]
>>>lst_eq1
[4,16]

scores = [88,90,100,65,78]
score_dic = {student_id :score for student_id,score in enumerate(scores)}

>>>score_dic
{0: 88, 1: 90, 2: 100, 3: 65, 4: 78}

enumerate是一個函數,當它與for 搭配時,他會同時把索引值與元素取出

1.7 輸入與輸出

print函式
1.任何基本資料都可以用print輸出
2.print 1,———不斷行列印 加逗號

input函式
guess = 6
while True:
guess_number = int(input('please enter a num \n'))
if guess_number == guess:
print "right"
break
else:
print “wrong"
注意:任何輸入都會被當成字串,需要轉換



[python] selenium 爬蟲安裝指南

http://www.kenst.com/2015/03/installing-chromedriver-on-mac-osx/

1.First, you need to download chromedriver
2.create a path for chromedriver

sudo nano /etc/paths

add path of chromedriver
ex: /Users/jackli/Documents/webdriver

To check:
echo $PATH

3.move chromedriver to your own path