文件 文件和文件夾 文件:文本文件、二進位文件 文件夾:(windows) G:\pythonWorkspace\python\study (linux/mac) /home/workspace/python 註意:文件夾路徑的斜杠linux與windows不同 windows下文件路徑:示例 跨平 ...
文件
文件和文件夾
文件:文本文件、二進位文件
文件夾:(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 python aaaaa >>> f =open(p2) #第二次也要open文件 >>> for line in f: ... print line, #出現空行解決方式在line後面加, ... study python aaaaa >>>
寫文件
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 line 7 ... 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)可選,它是以行為單位返回一個字元串,每次讀取一行,依次迴圈往下讀取,如果沒有參數,則將讀取到文件最後,返回空字元串,到達文件末尾。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 maximum 18 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 the 29 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 line 17 ... 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 line 32 ... 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 26L 49 >>> f.seek(4) #參數為4,將指針定位到從開頭到第4個字元的位置的後面 50 >>> f.tell() 51 4L 52 >>>