Python 學習筆記(十二)Python檔案和迭代(一),

來源:互聯網
上載者:User

Python 學習筆記(十二)Python檔案和迭代(一),

檔案

檔案和檔案夾

檔案:文字檔、二進位檔案

檔案夾:(windows) G:\pythonWorkspace\python\study   

    (linux/mac) /home/workspace/python

    注意:檔案夾路徑的斜杠linux與windows不同

windows下檔案路徑:樣本 

1 >>> p1="G:\pythonWorkspace\python\study\test.txt"2 >>> p2 =r"G:\pythonWorkspace\python\study\test.txt"3 >>> p3 ="G:\\pythonWorkspace\\python\\study\\test.txt"

 

跨平台路徑:os.path.abspath(path)

查看屬性:os.stat(filename)


p2 =r"G:\pythonWorkspace\python\study\test.txt"
1 >>> import os #引入os 模組
2 >>> os.stat(p2) #查看檔案屬性 3 nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0L, st_nlink=0, st_uid=0, st_gid=0, st_size=14L, st_atime=1520953379L, st_mtime=1520953401L, st_ctime=1520953379L) 4 >>>

 

讀、寫檔案

python 中檔案也是一種類型的對象,有屬性 __iter__,說明是可迭代的

開啟一個檔案

>>> dir(file)  #查看檔案的屬性['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']>>> f =open(p2) #開啟一個檔案>>> for line in f:  #迴圈讀取檔案內容...     print line #列印出來後,兩行之間有空行,原因print 會自動的帶上一個分行符號...study pythonaaaaa>>> f =open(p2) #第二次也要open檔案>>> for line in f:...     print line, #出現空行解決方式在line後面加,...study pythonaaaaa>>>

寫檔案

w 模式 開啟一個檔案只用於寫入。如果該檔案已存在則將其覆蓋。如果該檔案不存在,建立新檔案

a 模式 開啟一個檔案用於追加。如果該檔案已存在,檔案指標將會放在檔案的結尾。也就是說,新的內容將會被寫入到已有內容之後。如果該檔案不存在,建立新檔案進行寫入。

with 語句 可以不寫close() 

1 >>> nf =open("G:\\pythonWorkspace\\python\\study\\test.txt","w") #開啟一個檔案,用w模式,寫入2 >>> nf.write("This is a new file.") #將這句話寫入檔案3 >>> nf.close() #開啟一個檔案,寫入後必須關閉掉4 >>> nf =open("G:\\pythonWorkspace\\python\\study\\test.txt")5 >>> for line in nf:6 ...     print line7 ...8 This is a new file.
 1 >>> with open("G:\\pythonWorkspace\\python\\study\\test.txt","a") as fp:  #with open 也可以建立檔案 開啟檔案,適用with open write後面的close()可以不寫,它會自動處理 2 ...     fp.write("\n what's your name?") 3 ... 4  5 >>> f =open("G:\\pythonWorkspace\\python\\study\\test.txt") 6 >>> for line in f: 7 ...     print line 8 ... 9 10 11  what's your name?12 >>>

不同的讀檔案方法

 1 >>> help(file.read) 2 Help on method_descriptor:
  #參數size可選,如果沒有參數,將檔案的全部內容讀取,如果有參數,將讀取到指定的位元組,然後將讀取到的這些內容以字串形式返回 3 所讀取的內容一次返回到記憶體中,隨時可以取用,方便快捷。這種方式,如果檔案特別大的時候,會使記憶體開銷太大。 4 read(...) 5 read([size]) -> read at most size bytes, returned as a string. 6 7 If the size argument is negative or omitted, read until EOF is reached. 8 Notice that when in non-blocking mode, less data than what was requested 9 may be returned, even if no size parameter was given.10 11 >>> help(file.readline)12 Help on method_descriptor: 13 參數(size)可選,它是以行為單位返回一個字串,每次讀取一行,依次迴圈往下讀取,如果沒有參數,則將讀取到檔案最後,返回Null 字元串,到達檔案末尾。END OF FILE (EOF)14 readline(...)15 readline([size]) -> next line from the file, as a string.16 17 Retain newline. A non-negative size argument limits the maximum18 number of bytes to return (an incomplete line may be returned then).19 Return an empty string at EOF.20 21 >>> help(file.readlines)22 Help on method_descriptor:23 返回以行為單位的列表,相當於執行readline, 得到每一行,然後把這一行的字串,作為列表中的元素,再放到一個列表中,最後將列表返回。24 readlines(...)25 readlines([size]) -> list of strings, each a line from the file.26 27 Call readline() repeatedly and return a list of the lines so read.28 The optional size argument, if given, is an approximate bound on the29 total number of bytes in the lines returned.

樣本:讀取檔案

  read()      讀取檔案內容,如果指定參數,將指定位元組相應的內容返回,如果沒有指定參數,將檔案內容全部返回。

  readline() 以行為單位讀取檔案,返回一個字串,每次讀取一行,一次迴圈往下讀取。如果沒有指定參數,將讀取到檔案末尾。

  readlines() 返回以行為單位的列表,相當於執行readline,得到每一行,然後把這一行的字串,作為列表的元素,最後將這個列表返回

  import fileinput 讀取大檔案時,使用 

  f.seek(0) 改變當前檔案的位置

  f.tell() 告訴檔案當前的指標位置,檔案內的當前位置

 1 >>> f =open("G:\\pythonWorkspace\\python\\study\\test.txt") 2 >>> c=f.read() #把檔案的全部內容讀取出來,放到一個變數 3 >>> c 4 "\n what's your name?" 5 >>> f =open("G:\\pythonWorkspace\\python\\study\\test.txt") 6 >>> f.read(5) #有參數,將返回相應位元組的內容 7 '\n wha' 8 >>> f =open("G:\\pythonWorkspace\\python\\study\\test.txt") 9 >>> f.readline() 返回第一行的內容,每一行都是一個字串10 '\n'11 >>> f =open("G:\\pythonWorkspace\\python\\study\\test.txt")12 >>> f.readlines()  返回一個列表,列表中每一行為一個元素13 ['\n', " what's your name?"]14 >>> import fileinput #引入大檔案模組,避免檔案太大,記憶體過滿的問題15 >>> for line in fileinput.input("G:\\pythonWorkspace\\python\\study\\bigfile.txt"):16 ...     print line17 ...18 Before getting started,19 20 you may want to find out which IDEs and text editors are tailored to make Python editing easy,21 22 browse the list of introductory books,23 24 or look at code samples that you might find helpful.25 26 There is a list of tutorials suitable for experienced programmers on the BeginnersGuide/Tutorials page.27 28 There is also a list of resources in other languages which might be useful if English is not your first language.29 >>> f=open("G:\\pythonWorkspace\\python\\study\\bigfile2.txt")30 >>> for line in f:31 ...     print line32 ...33 Before getting started,34 35 you may want to find out which IDEs and text editors are tailored to make Python editing easy,36 37 browse the list of introductory books,38 39 or look at code samples that you might find helpful.40 41 There is a list of tutorials suitable for experienced programmers on the BeginnersGuide/Tutorials page.42 43 There is also a list of resources in other languages which might be useful if English is not your first language.
  #每次讀取完一個檔案之後,都需要重新把這個檔案再開啟一次,之所以這樣做是因為指標已經移到檔案最後了。44 >>> f.seek(0) #使用seek()移動指標,參數0為,指標回到檔案最開始,45 >>> f.readline()46 'Before getting started, \n'47 >>> f.tell() #使用tell()查看當前指標的位置48 26L49 >>> f.seek(4) #參數為4,將指標定位到從開頭到第4個字元的位置的後面50 >>> f.tell()51 4L52 >>>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.