1. 程式人生 > >python資料結構之列表、字典、元組、集合

python資料結構之列表、字典、元組、集合

列表

列表在python裡是有序集合物件型別。
列表裡的物件可以是任何物件:數字,字串,列表或者字典,元組。與字串不同,列表是可變物件,支援原處修改的操作
python的列表是:

  • 任意物件的有序集合
  • 通過偏移讀取
  • 可變長度、異構以及任意巢狀
  • 屬於可變序列的分組
  • 物件引用陣列

列表的操作

列表的操作和字串大部分都相同:
合併/重複:

  • list1+list2:結果是兩個列表按順序結合
  • list*3:結果是列表list重複三次
  • for i in list1: print(i):按順序列印列表裡的內容
  • 3 in list:判斷列表裡有沒有一個物件是物件3
  • list1.index(1):查詢列表裡第一個為1的物件的位置
  • list1.count(1):查詢列表裡物件為1的個數
  • list1[x:y]:取第x到y的物件,重新建立一個列表
  • len(list1):list1裡的物件個數
基本列表操作

建立一個列表:

>>> list=[]
>>> list=[1,2,'3',[]]
>>> list
[1, 2, '3', []]

列表取值:

>>> list[1]
2
>>> list[0:3]
[1, 2, '3']

重複列表內容:

>>> list*3
[1, 2, '3', [], 1, 2, '3', [], 1, 2, '3', []]

使用in方法來判斷物件是否在列表中:

>>> 3 in list
False
>>> [] in list
True

迴圈列印:

>>> for i in list:
...     print (i,end=' ')
...
1 2 3 [] 

迭代方式建立列表:

>>> list=[i*4 for i in 'ASDF' ]
>>> list
['AAAA', 'SSSS', 'DDDD', 'FFFF']

矩陣:

list=[ [1,2,3,],[4,5,6],[7,8,9] ]
>>> list
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> list[0][1]
2
>>> list[1][2]
6

列表原處修改:

>>> food=['spam','eggs','milk']
>>> food[1]
'eggs'
>>> food[1]='Eggs'
>>> food[:]
['spam', 'Eggs', 'milk']
列表的方法
  • 列表的新增:
>>>food.append('cake')  
>>> food
['spam', 'Eggs', 'milk', 'cake']
  • 列表的排序:
>>> food.sort()    
>>> food
['Eggs', 'cake', 'milk', 'spam']
  • 合併列表:
    >>> list1=[1,2,3]
    >>> list2=[4,5,6]
    >>> list1.extend(list2)
    >>> list1
    [1, 2, 3, 4, 5, 6]
  • 列表的取值:
    >>> list1.pop()
    6
    >>> list1
    [1, 2, 3, 4, 5]
  • 列表倒序顯示:
    >>> list1
    [1, 2, 3, 4, 5]
    >>> list1.reverse()
    >>> list1
    [5, 4, 3, 2, 1]
  • 列表的索引:
    >>> list=[1,2,3,4,5]
    >>> list.index(3)
    2
  • 列表的插入:
    >>> list.insert(2,10)
    >>> list
    [1, 2, 10, 3, 4, 5]
  • 刪除列表的某一個物件:
    >>> list
    [1, 2, 10, 3, 4, 5]
    >>> del list[2]
    >>> list
    [1, 2, 3, 4, 5]
  • 列表的排序:
    列表的排序預設是先以字母大小寫進行排序的,可以在列表中加一個選項key=lower.str使其都轉換成小寫,使用reverse=True進行倒序排列
>>> list=['abc','aDd','ace']
>>> sorted(list)
['aDd', 'abc', 'ace']
>>> list
['abc', 'aDd', 'ace']
>>> sorted(list,key=str.lower,reverse=True)
['aDd', 'ace', 'abc']
>>> sorted(list,key=str.lower)
['abc', 'ace', 'aDd']
>>>sorted([x.lower() for x in list])
['abc', 'ace', 'add']
>>> sorted([x.lower() for x in list],reverse=True)
['add', 'ace', 'abc']
列表的實際用法
  • 取值:
    >>> info=['myname',18,[1997,9,28]]
    >>> _name,_age,_birth=info
    >>> _name
    'myname'
    >>> _age
    18
    >>> _birth
    [1997, 9, 28]
    >>> _name,_age,(_birth_y,_birth_m,_birth_d)=info
    >>> _birth_y
    1997
    >>> _birth_m,_birth_d
    (9, 28)

    當取的值不固定的時候,可以用*代替:

    >>> a=['adc',122,2215,'[email protected]']
    >>> a_name,*a_phone,a_mail=a
    >>> a_name
    'adc'
    >>> a_phone
    [122, 2215]
  • 只保留列表裡最後N個元素:
    使用deque函式可以設定列表中的元素個數,如果超過列表最大限制,那麼會將列表裡最左邊的元素刪掉,如果是在左邊新增的,那麼刪除的是最右邊的元素
    >>> from collections import deque
    >>> q=deque(maxlen=3)
    >>> q.append(1)
    >>> q.append(2)
    >>> q.append(3)
    >>> q
    deque([1, 2, 3], maxlen=3)
    >>> q.append(4)
    >>> q
    deque([2, 3, 4], maxlen=3) 
    >>> q.appendleft('5')
    >>> q
    deque(['5', 2, 3], maxlen=3)
  • 取出列表中的最大值和最小值:
    使用heapq模組的nlargest,nsmallest方法來取出列表中的幾個最大值和最小值,當然也可以使用max和min函式來求最大和最小,使用sum函式來求列表數字的和
    >>> from heapq import nlargest,nsmallest
    >>> num=[1,4,6,7,8,8,34,64,23,7,45,34]
    >>> nlargest(3,num)
    [64, 45, 34]
    >>> nlargest(2,num)
    [64, 45]
    >>> nsmallest(2,num)
    [1, 4]
    >>> nsmallest(4,num)
    [1, 4, 6, 7]
    >>> num
    [1, 4, 6, 7, 8, 8, 34, 64, 23, 7, 45, 34]
    >>> max(num)
    64
    >>> min(num)
    1
    >>> sum(num)
    241
    >>> a_info=['wanger','wangerxiao',25,'computer']
    >>> _name=slice(0,2)
    >>> _age=slice(2,3)
    >>> _job=slice(3,4)
    >>> a_info[_name]
    ['wanger', 'wangerxiao']
    >>> a_info[_age]
    [25]
    >>> a_info[_job]
    ['computer']
  • 重複元素計算:
    這會用到collections模組的Counter方法
    >> a=[1,2,3,4,5,6,2,4,2,5,6]
    >>> from collections import Counter
    >>> count_word=Counter(a)
    >>> count_word
    Counter({2: 3, 4: 2, 5: 2, 6: 2, 1: 1, 3: 1})
    >>> count_word.most_common(3)
    [(2, 3), (4, 2), (5, 2)]
    >>> count_word.most_common(2)
    [(2, 3), (4, 2)]

    字典

    字典在python裡是無序集合物件型別。
    字典的值都有獨立的唯一的鍵,用相應的鍵來取值。
    python字典主要特性如下:

  • 通過鍵而不是偏移量來讀取
  • 任意物件的無序組合
  • 可變長,異構,任意巢狀
  • 屬於可對映型別
  • 物件引用表

字典用法注意事項:

  • 序列運算無效——串聯,分片不能使用
  • 對新索引(鍵)賦值會新增項
  • 鍵不一定是字串——只要是不可變的物件(列表字典除外)

字典的基本操作:

  • 字典的賦值:

    >>> dict={'a':97,'b':98}
    >>> len(dict)
    2
    >>> print("ascii code of 'a' is {},ascii code of 'b' is {}".format(dict['a'],dict['b']))
    ascii code of 'a' is 97,ascii code of 'b' is 98
  • 判斷特定的鍵是否存在於字典裡:

    >>> 'a' in dict
    True
    >>> 'b
    >>>> 'b' is in dict
    True
  • 原處修改:
    #更改特定鍵的值
    >>> food={'eggs':3,'ham':1,'spam':4}
    >>> food['ham']=2
    >>> food
    {'eggs': 3, 'ham': 2, 'spam': 4}
    #增加新的鍵和相應的值
    >>> food['branch']=['bacon','bake']
    >>> food
    {'eggs': 3, 'ham': 2, 'spam': 4, 'branch': ['bacon', 'bake']}
    #刪除一個字典元素
    >>> del food['eggs']
    >>> food
    {'ham': 2, 'spam': 4, 'branch': ['bacon', 'bake']}
    #清空字典所有條目
    >>> dict.clear()
    #刪除字典
    del dict

    字典的方法

  • 查詢字典的鍵值是否存在,如果不存在可以設定返回的值

    >>> food.get('ham')
    2
    >>> dict.get('b')
    2
    >>> dict.get('0')
    >>> dict.get('0','none')
    'none'
  • 建立字典的方法:
    1.最原始的方法:

    dict={'name':'wanger','age':25}

    2.按鍵賦值方法:

    >>> dict={}
    >>> dict['name']='wanger'
    >>> dict['age']=25
  • 字典的比較:
    字典的比較會比較字典的鍵,而不是字典的值,可以使用zip方式將字典的值和鍵反過來,這樣就會比較值了,可以使用sorted函式對字典進行排序

    >>> dict={'a':1,'b':2,'c':3,'d':4}
    >>> max(dict)
    'd'
    >>> min(dict)
    'a'
    >>> max(zip(dict.values(),dict.keys()))
    (4, 'd')
    >>> min(zip(dict.values(),dict.keys()))
    (1, 'a')
    >>> sorted(zip(dict.values(),dict.keys()))
    [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
    >>> sorted(zip(dict.values(),dict.keys()),reverse=True)
    [(4, 'd'), (3, 'c'), (2, 'b'), (1, 'a')]
  • 字典列表的排序:
    可以使用sorted函式進行排序,使用key引數可以對排序的鍵進行定義,這裡要用到operator模組的itemgetter函式
    >>> rows
    [{'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},
    {'fname': 'David', 'lname': 'Beazley', 'uid': 1002}, 
    {'fname': 'John', 'lname': 'Clesse', 'uid': 1001},
    {'fname': 'Big', 'lname': 'Jones', 'uid': 1004}]
    >>> from operator import itemgetter
    >>> rows_fname=sorted(rows,key=itemgetter('fname'))
    >>> rows_fname
    [{'fname': 'Big', 'lname': 'Jones', 'uid': 1004},
    {'fname': 'Brian', 'lname':
    'Jones', 'uid': 1003}, 
    {'fname': 'David', 'lname': 'Beazley', 'uid': 1002}, 
    {'fname': 'John', 'lname': 'Clesse', 'uid': 1001}]
    >>> rows_uid=sorted(rows,key=itemgetter('uid'))
    >>> rows_uid
    [{'fname': 'John', 'lname': 'Clesse', 'uid': 1001}, 
    {'fname': 'David', 'lname': 'Beazley', 'uid': 1002}, 
    {'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},
    {'fname': 'Big', 'lname': 'Jones', 'uid': 1004}]

元組

元組簡介

元組與列表非常類似,只是不能在原處更改,元祖在python裡的特點:

  • 任意物件的有序組合
  • 通過偏移取資料
  • 屬於不可變序列型別
  • 固定長度,異構,任意巢狀
  • 物件引用的陣列

元組的建立

元祖建立在只有單個元素的時候,必須加逗號(,),元組裡可以巢狀元組

>>> tuple=()
>>> tuple=(1,)
>>> type(tuple)
<class 'tuple'>
#這裡加不加括號都一樣
>>> tuple=(1,2,'3',(4,5))
>>> tuple
(1, 2, '3', (4, 5))
>>> tuple=1,2,'3',(4,5)
>>> tuple
(1, 2, '3', (4, 5))

將列表轉換為元組

>>> list=[1,2,3,4]
>>> sd=tuple(list)
>>> sd
(1, 2, 3, 4)

元組的方法

  • 元組的排序:
    元組經過sorted排序後,會將其轉換為列表

    >>> tuple=(1,5,3,6,4,2)
    >>> sorted(tuple)
    [1, 2, 3, 4, 5, 6]
  • 查詢元組元素位置:
    >>> tuple
    (1, 5, 3, 6, 4, 2)
    >>> tuple.index(3)
    2
  • 計算元組元素數目:

    >>> tuple
    (1, 5, 3, 6, 4, 2)
    >>> tuple.count(3)
    1
  • 元組的切片:

    >>> tuple[0]
    1
    >>> tuple[2:]
    (3, 6, 4, 2)
    >>> tuple[2:3]
    (3,)
  • 列表和元組的操作類似,列表操作裡只要不是在原處修改的,都可用於元組
    >>> (1,2)+(3,4)
    (1, 2, 3, 4)
    >>> (1,2)*4
    (1, 2, 1, 2, 1, 2, 1, 2)
    >>> len(tuple)
    6

    集合

    集合簡介

    set是一個無序且不重複的元素集合
    集合物件十一組無序排列的可雜湊的值,集合成員可以做字典中的鍵。set也支援用in 和not in操作符檢查成員,由於集合本身是無序的,不可以為集合建立索引或執行切片操作,也沒有鍵可用來獲取集合中元素的值。

集合特點

  • 集合中的元素和字典中的鍵一樣不重複
  • 集合中的元素為不可變物件

集合的建立

>>> s=set('a')
>>> a=set({'k1':1,'k2':2})
>>> b=(['y','e','d','o'])
>>> c={'a','b','c'}
>>> d={('a','b','c')}

集合基本操作

  • 集合的比較
    #比較a、b集合中a中存在,b中不存在的集合
    >>> a={11,22,33}
    >>> b={11,23,45}
    >>> a.difference(b)
    {33, 22}
    #找到a中存在,b中不存在的集合,並把a、b集合中都有的值覆蓋掉
    >>> a={11,22,33}
    >>> print(a.difference_update(b))
    None
    >>> a
    {33, 22}
  • 集合的刪除:

    >>> a={11,22,33}
    >>> a.discard(11)
    >>> a.discard(44)
    >>> a
    {33, 22}
    #移除不存在的元素會報錯
    >>> a={11,22,33}
    >>> a.remove(11)
    >>> a.remove(44)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    KeyError: 44
    >>> a
    {33, 22}
    #移除末尾的元素
    >>> a={11,22,33}
    >>> a.pop()
    33
    >>> a
    {11, 22}
  • 取交集:

    #取交集賦給新值
    >>> a={1,2,3,4}
    >>> b={6,5,4,3}
    >>> print (a.intersection(b))
    {3, 4}
    #取交集並把交集賦給a
    >>> print (a.intersection_update(b))
    None
    >>> a
    {3, 4}
  • 集合判斷:
    >>> a={3,4}
    >>> b={6,5,4,3}
    #判斷a是否與b沒有交集,有交集False,無交集True
    >>> a.isdisjoint(b)
    False
    #判斷a是否是b的子集
    >>> a.issubset(b)
    True
    #判斷a是否是b的父集
    >>> a.issuperset(b)
    False
  • 集合合併:
    >>> a={1,2,3,4}
    >>> b={3, 4, 5, 6}
    #列印不同的元素
    >>> print (a.symmetric_difference(b))
    {1, 2, 5, 6}
    #列印不同的元素,並覆蓋到集合a
    >>> print (a.symmetric_difference_update(b))
    None
    >>> a
    {1, 2, 5, 6}
  • 集合取並集:
    >>> a={1, 2, 5, 6}
    >>> b={3, 4, 5, 6}
    >>> print (a.union(b))
    {1, 2, 3, 4, 5, 6}
  • 集合的更新:

    >>> a={1, 2, 5, 6}
    >>> b={3, 4, 5, 6}
    #把a、b的值合併,並把值賦給集合a
    >>> a.update(b)
    >>> a
    {1, 2, 3, 4, 5, 6}
    #新增a集合的元素
    >>> a.update([7,8])
    >>> a
    {1, 2, 3, 4, 5, 6, 7, 8}
  • 集合的轉換:
    將集合分別轉換為列表、元組、字串
    >>> a=set(range(5))
    }
    >>> li=list(a)
    >>> tu=tuple(a)
    >>> st=str(a)
    >>> print (li)
    [0, 1, 2, 3, 4]
    >>> print (tu)
    (0, 1, 2, 3, 4)
    >>> print (st)
    {0, 1, 2, 3, 4}

python檔案

檔案簡介

檔案物件在python裡可以作為作業系統上的檔案的連結
檔案物件的使用方式與之前的字串、列表等物件不同,它是對檔案的輸入、輸出進行控制
在python裡會用open函式來進行檔案的控制

檔案的訪問

在python裡使用open函式可以訪問檔案。
基本格式是:open(<file_address>[,access_mode])
這裡的檔案地址是文字形式,在Windows裡由於檔案地址是使用反斜槓(),所以,可以使用r來對反斜槓不進行轉義。
例如:
open(r'C:\mydir\myfile')
訪問模式裡是引數,預設是r(讀取)
在訪問模式,每一種方法都有一種使用到b的方式,就是二進位制模式。
檔案的讀寫引數

操作說明符 解釋
r 以只讀方式開啟檔案,這是預設模式
rb 以二進位制格式開啟一個檔案用於只讀。這是預設模式
r+ 開啟一個檔案用於讀寫
rb+ 以二進位制格式開啟一個檔案用於讀寫
w 開啟一個檔案只用於寫入。檔案存在則覆蓋,不存在,則建立新檔案
wb 以二進位制格式開啟一個檔案只用於寫入。檔案存在則覆蓋,不存在則建立
w+ 開啟一個檔案用於讀寫。如果檔案已存在則將其覆蓋,不存在則建立新檔案。
wb+ 以二進位制開啟一個檔案用於讀寫。如果該檔案存在則覆蓋,不存在則建立
a 開啟一個檔案用於追加,如果檔案內容存在,則將新內容追加到檔案末尾,不存在則建立新檔案寫入
ab 以二進位制格式開啟一個檔案用於寫入
a+ 開啟一個檔案用於讀寫,如果該檔案存在,則會將新的內容追加到檔案末尾,如果檔案不存在,則建立新檔案用於讀寫。
ab+ 以二進位制格式開啟一個檔案用於追加,檔案存在將追加,不存在則建立新檔案用於讀寫

檔案的使用

  • 迭代器是最好的讀行工具,比如使用for迴圈
  • 內容是字串,不是物件,檔案讀取完之後,內容是以字串的形式讀取的。
  • close是通常選項,當你使用完檔案後,使用close方法來關閉檔案關聯
  • 檔案是緩衝而且是可查詢的,flush或close()方法可以直接儲存快取裡的內容,seek方法可以轉到指定位置,當我們使用檔案的時候,跟其他物件一樣,用一個變數來引用

例子

>>> file1=open(r'D:\ruanjian\1.txt','w')
>>> file1.write('hello,world')
11
>>> file1.close()
>>> file1=open(r'D:\ruanjian\1.txt')
>>> file1.read()
'hello,world'
#tell用於獲取檔案指標位置,檔案讀取之後,檔案指標在最後面
>>> file1.tell()
11
>>> file1.close()
>>>> file1=open(r'D:\ruanjian\1.txt')
>>> file1.seek(6)
6
>>> file1.read(5)
'world'

檔案的讀取

當我們要讀取前五個字元的時候可以這樣:

>>> file1=open(r'D:\ruanjian\1.txt')
>>> file1.read(5)
'hello'
>>> file1.tell()
5

當我們要按行讀取的時候,可以使用readline和readlines方法

>>> file1=open(r'D:\ruanjian\1.txt')
>>> file1.readline()
'hello,world\n'
>>> file1.readline()
'wanger\n'
>>> file1.readline()
'asdfgghh'
>>> file1.readline()
''
>>> file1=open(r'D:\ruanjian\1.txt')
>>> file1.readlines()
['hello,world\n', 'wanger\n', 'asdfgghh']

檔案的寫入

當我們需要寫入到一個檔案的時候,會使用w模式。當相應的檔案存在時,會覆蓋原先的檔案然後寫入,當相應的檔案不存在時會建立新檔案。

  • 基本寫入

    >>> file=open(r'D:\ruanjian\1.txt','w')
    >>> file.write('hello,world')
    11
    >>> file.write('|wanger')
    7
    >>> file.flush()
    >>> file.close()
    >>> file=open(r'D:\ruanjian\1.txt')
    >>> file.read()
    'hello,world|wanger'

    在這裡flush()方法是把快取裡的內容寫入硬碟中。當執行close()方法的時候,也會進行同樣操作。

  • 按列表寫入:
    writelines是把列表裡的元素一個一個輸入進去。當然,元素裡的字串最後沒有換行,最終結果也不是換行的。

    >>> list=['hello,world!\n','wanger\n','asdfgh\n']
    >>> file=open(r'D:\ruanjian\1.txt','w')
    >>> file.writelines(list)
    >>> file.close()
    >>> file=open(r'D:\ruanjian\1.txt')
    >>> file.read()
    'hello,world!\nwanger\nasdfgh\n'
  • 在特定位置寫入
    當我們輸入錯誤的時候,可以把指標挪到最前面,然後繼續輸入。seek可以有兩個傳遞變數,只有一個變數或者第一個變數為0時,就是更改當前的指標,第二個變數為1的時候,會返回當前指標位置,這個與tell方法同樣,最後,第一個變數為0,第二個變數為2的時候會把指標放到最後

    >>> file=open(r'D:\ruanjian\1.txt','w')
    >>> file.write('heelo')
    5
    >>> file.seek(0)
    0
    >>> file.write('hello')
    5
    >>> file=open(r'D:\ruanjian\1.txt')
    >>> file.read()
    'hello'
  • 在最後寫入
    之前看到的w模式,當檔案是已有檔案,就會刪除裡面的所有內容後再寫入的。當我們需要在最後新增,而不是刪除原有內容時,可以使用a模式。

    >>> file=open(r'D:\ruanjian\1.txt')
    >>> file.read()
    'hello'
    >>> file.close()
    >>> file=open(r'D:\ruanjian\1.txt','a')
    >>> file.write('my name is wanger')
    17
    >>> file=open(r'D:\ruanjian\1.txt')
    >>> file.read()
    'hellomy name is wanger'

    在模式裡,我們會看到r+,w+,a+三種模式都有讀寫的方法。
    r+模式,只能開啟已有檔案,開啟時保留原有檔案,對檔案可讀,可寫,也可更改原有內容。開啟是指標在檔案最前面。
    w+模式,開啟時沒有相應的檔案,會建立;有相應的檔案會覆蓋原有的內容
    a+模式,可以開啟原有檔案,也可建立新的檔案,開啟時指標為檔案的最後位置。指標可以放到任何位置來讀內容,但寫入時,指標預設會移動到最後,然後寫入。

模式 開啟已有檔案 開啟新的檔案 開啟時指標位置 寫入時指標位置
r+ 保留內容 發生錯誤 檔案開頭 當前位置
w+ 刪除內容 建立檔案 檔案開頭 當前位置
a+ 保留內容 建立檔案 檔案尾端 檔案尾端

檔案的訪問

  • 二進位制模式
    在這個模式中,在python2.x中不會有什麼特別,因為在2.x裡儲存方式就是二進位制方式,但在python3.x裡是Unicode方式。
    >>> cha='啊'
    >>> cha_b=cha.encode()
    >>> file=open(r'D:\ruanjian\1.txt','w')
    >>> file.write(cha)
    1
    >>> file.write(cha_b)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: write() argument must be str, not bytes
    >>> file.close()
    >>> file=open(r'D:\ruanjian\1.txt')
    >>> file.read()
    '啊'
    >>> file=open(r'D:\ruanjian\1.txt','wb')
    >>> file.write(cha)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: a bytes-like object is required, not 'str'
    >>> file.write(cha_b)
    3
    >>> file.close()
    >>> file=open(r'D:\ruanjian\1.txt','rb')
    >>> file.read()
    b'\xe5\x95\x8a'

檔案與其他型別

  • 原生物件的存取
    儲存一些物件的時候,比如說列表,字典等;python都需要把這些物件轉換成字串後儲存:
    >>> file=open(r'D:\ruanjian\1.txt','w')
    >>> file.write({'a':97})
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: write() argument must be str, not dict
    >>> file.write(str({'a':97}))
    9
    >>> file.write(str([1,2]))
    6
    >>> file.close()
    >>> file=open(r'D:\ruanjian\1.txt')
    >>> file.read()
    "{'a': 97}[1, 2]"

如果要將儲存的字串轉換回原來的資料型別,可以用pickle模組:

>>> file=open(r'D:\ruanjian\1.txt','wb')
>>> a={'a':97}
>>> pickle.dump(a,file)
>>> file.close()
>>> file=open(r'D:\ruanjian\1.txt','rb')
>>> a_=pickle.load(file)
>>> a_
{'a': 97}

列印輸出至檔案

需要把列印的內容直接輸出到檔案裡的時候:

>>> with open (r'D:\ruanjian\1.txt','w') as f:
...     print ('hello,world!',file=f)
...
>>> with open (r'D:\ruanjian\1.txt') as f:
...     f.read()
...
'hello,world!\n'

判斷檔案是否存在,不存在時寫入

因為w方式對已存在的檔案會清楚後寫入,但有的時候我們不想覆蓋原有的檔案,我們可以使用如下方式:

>>> if not os.path.exists(r'D:\ruanjian\1.txt'):
...     with open(r'D:\ruanjian\1.txt','wt') as f:
...             f.write('hello,world')
... else:
...     print ('file already exists')
...
file already exists

在python3.x中我們也可以使用這種方式來判斷檔案是否存在,存在的話會報錯,不存在的話檔案可以建立

>>> with open(r'D:ruanjian\2.txt','xt') as f:
...     f.write('hello\n')
...
6
>>> with open(r'D:ruanjian\2.txt','xt') as f:
...     f.write('hello\n')
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists: 'D:ruanjian\\2.txt'

讀寫壓縮檔案

檔案在儲存時也可以壓縮儲存,需要用到gzip或者bz2模組,在這兩個模組中,預設是二進位制模式,因此需要使用wt,rt等,指定text模式。讀的時候使用rt,和read()。
壓縮級別可以用compresslevel來設定,也可以使用open裡的encoding,errors,newline等。

>>> with gzip.open(r'D:\ruanjian\1.gz','wt') as f:
...     f.write('text')
...
4
>>> with gzip.open(r'D:\ruanjian\1.gz','rt') as f:
...     f.read()
...
'text'
>>> with bz2.open(r'D:\ruanjian\1.bz2','wt') as f:
...     f.write('hello,world')
...
11
>>> with bz2.open(r'D:\ruanjian\1.bz2','rt') as f:
...     f.read()
...
'hello,world'

獲取資料夾中的檔案列表

這要用到os模組裡的方法,關於os模組可以檢視公眾號的歷史訊息,對os模組有詳細的解釋,這裡只列出一些簡單的方法:

>>> import os
>>> os.getcwd()
'/root/blog'
>>> os.listdir('.')
['_config.yml', 'node_modules', '.gitignore', 'source', 'db.json', 'themes', 'package.json', 'public', 'scaffolds', '.deploy_git']
#當需要判斷是檔案時
>>> files=[file for file in os.listdir('.') if os.path.isfile(os.path.join('.',file))]
>>> files
['_config.yml', '.gitignore', 'db.json', 'package.json']

歡迎各位關注我的微信公眾號
python資料結構之列表、字典、元組、集合