Python學習(六)——迭代、檔案讀寫__Python

來源:互聯網
上載者:User

迭代
迭代通過for…in…實現
①list

>>> l=['Ryan','Rick','Morty']>>> for key in l:    print keyRyanRickMorty

②tuple

>>> t=('Ryan','Rick','Morty')>>> for key in t:    print keyRyanRickMorty

③字串

>>> for k in 'abcdefgh':    print kabcdefgh

④字典
(dict的儲存順序不是按list順序排列的)
迭代key:

>>> d={'name01':'Ryan','name02':'Rick','name03':'Morty'}>>> for key in d:    print keyname03name02name01

迭代value:

>>> d={'name01':'Ryan','name02':'Rick','name03':'Morty'}>>> for value in d.iteritems():    print value('name03', 'Morty')('name02', 'Rick')('name01', 'Ryan')

同時迭代key和value:

>>> for key,value in d.iteritems():    print key,valuename03 Mortyname02 Rickname01 Ryan

⑤同時迭代多個變數:

>>> for x,y,z in [('a',1,4),('b',4,8),('d',7,9),('s',5,89)]:    print x,y,za 1 4b 4 8d 7 9s 5 89

⑥利用enumerate函數將list變成索引-元素對:

>>> L=[12,56,789,15,5,89,45,34]>>> for i,v in enumerate(L):    print i,v0 121 562 7893 154 55 896 457 34

⑦判斷一個對象是否可以迭代:

>>> from collections import Iterable>>> isinstance('Ryan',Iterable)True>>> isinstance(12345,Iterable)False

檔案讀寫

1 open()函數
flie_obj = open(filename, mode=’r’,buffering = -1)

filename為傳入檔案名稱
mode為選擇性參數,預設值為r,(’r’讀,’w’寫,’rb’讀二進位檔案<映像、視頻等>,’wb’寫二進位檔案)
buffering預設值為-1(表示系統預設的緩衝方式),為選擇性參數(0代表不緩衝,1或大於1的值表示緩衝一行或指定緩衝區大小)

>>> f1=open('F:/data.txt','r')>>> print f1.read()Hello,world!>>> f1.close()
>>> f2=open('F:/data.txt','w')>>> f2.write('abcdefg')>>> f2.close()

讀取非ASCII碼文字檔時,必須以二進位模式開啟,再解碼。如GBK編碼檔案:

f=open('F:/data.txt','r')u=f.read().decode('gbk')print uf.close()

(data.txt檔案中內容為中文)
或使用codecs模組:

import codecswith codecs.open('F:/data.txt','r','gbk') as f:    print f.read()

2 readlines()函數
file_obj.readlines()
將資料從檔案中一行一行的讀取出來,返回一個list(包含分行符號);

3 readline()函數
file_obj.readline()
讀取檔案中的第一行資料,返回一個字串;

4 seek()函數
file_obj.seek(offet, whence=0)
在檔案中移動檔案指標,從whence(0表示檔案頭部,1表示當前位置,2表示檔案尾部)位移offset個位元組;
whence參數可選,預設值為0.

5 split()函數
split(self, sep=None, maxsplit=None)
split()函數:指定分隔字元對字串進行分割,參數1為指定的分隔字元,參數2為分割的字串個數;

s = "40920  8.326976    0.953952    320 8.326976    0.953952"print s.split('\t')print s.split('\t',2)

輸出:

['40920', '8.326976', '0.953952', '320', '8.326976', '0.953952']['40920', '8.326976', '0.953952\t320\t8.326976\t0.953952']

6 strip()函數
截取掉所有的斷行符號字元

檔案關閉

使用 try…finally 保證無論是否出錯都能正確關閉檔案

try:    f=open('F:/data.txt','r')    print f.read()finally:    if f:        f.close()

或利用 with 語句:

with open('F:/data.txt','r') as f:    print f.read()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.