python 文件讀寫
w 讀
r 寫
a 附加 (append)
my_file = open('myfile.txt','w')
my_file.write("XD")
my_file.close
file = open('myfile.txt','r')
content = file.read()
content_arr = file.readlines() // 以 array 方式逐行儲存
print(content)
目前這樣容易會忘了關檔,這時候用 with 是個不錯的選擇
python tuple & list
a_tuple = (1,2,3,4)
another_tuple = 2,4,6,8,10
a_list = [1,2,3,4,5]
a_list.sort(reverse=True)
print(a_tuple)
print(another_tuple)
print(a_list)
python dictionary
dic = {'key1':1,'key2':2,'key3':3, 4:'haha'}
dic2 = {'pear':{1:3, 3:'a'}, 'orange':'2017'}
print(dic)
print(dic['key1'])
print(dic[4])
print(dic2['pear'][3])
dic['new'] = 99
del dic['key2']
print(dic)
python set
利用 set (集合) 來找出所有不重複的元素
my_set = ['a','a','a','b','b','c','c','c','c','d','e','ee','e']
print(set(my_set))
sentence = 'Today is Tuesday, said tao'
print(set(sentence))
unique_char=set(my_set)
unique_char.add('x')
unique_char.remove('a')
print(unique_char)
set1 = set(my_set)
set2 = set(sentence)
print(set1.intersection(set2))
print(set1.difference(set2))
python import module
import time
print(time.time())
print(time.localtime())
from time import time, localtime
print(time())
print(localtime())
python 例外處理
try:
file = open('ooxx','r')
except Exception as e:
print('no such file')
else:
file.write('XD')
file.close()
使用 pickle 存變數資料與運算結果
import pickle
a = [1,3,5,7,9]
d = {'cat':1000, 2:['1','a','XX',3], '3':{'k':'tao', 6:10}}
s = 'my name'
with open('my_file.pickle','wb') as file:
pickle.dump(a, file)
pickle.dump(d, file)
pickle.dump(s, file)
import pickle
with open('my_file.pickle','r') as file1:
a = pickle.load(file1)
d = pickle.load(file1)
s = pickle.load(file1)
print(a)
print(d)
print(s)
深複製(deep copy)與淺複製(shallow copy)
import copy
a = [1,2,3]
b = a
print(id(a))
print(id(b))
print(id(a)==id(b))
b[0] = 11
print(a)
a[1] = 22
print(b)
c = copy.copy(a)
print(id(a)==id(c))
c[1] = 22222
print(a)
print(c)
- assign, copy 與 deepcopy 的差別
import copy
a = [1,2,[3,4]]
b = a
print("*** assign ***")
print(id(a)==id(b))
print(id(a[2])==id(b[2]))
d = copy.copy(a)
print("*** shallow copy ***" )
print(id(a)==id(d))
print(id(a[2])==id(d[2]))
e = copy.deepcopy(a)
print("*** deep copy ***" )
print(id(a)==id(e))
print(id(a[2])==id(e[2]))
a[0] = 11
print(b)
print(d)
print(e)
a[2][0] = 333
print(b)
print(d)
print(e)
留言
張貼留言