Python文件操作学习总结
生活随笔
收集整理的這篇文章主要介紹了
Python文件操作学习总结
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Python讀寫文件
1.open
使用open打開文件后一定要記得調(diào)用文件對象的close()方法。比如可以用try/finally語句來確保最后能關(guān)閉文件。
file_object = open('thefile.txt')
try:
? ? ?all_the_text = file_object.read( )
finally:
? ? ?file_object.close( )
注:不能把open語句放在try塊里,因?yàn)楫?dāng)打開文件出現(xiàn)異常時(shí),文件對象file_object無法執(zhí)行close()方法。
2.讀文件
讀文本文件
input = open('data', 'r')
#第二個(gè)參數(shù)默認(rèn)為r
input = open('data')
讀二進(jìn)制文件
input = open('data', 'rb')
?
讀取所有內(nèi)容
file_object = open('thefile.txt')
try:
? ? ?all_the_text = file_object.read( )
finally:
? ? ?file_object.close( )
?
讀固定字節(jié)
file_object = open('abinfile', 'rb')
try:
? ? while True:
? ? ? ? ?chunk = file_object.read(100)
? ? ? ? if not chunk:
? ? ? ? ? ? break
? ? ? ? ?do_something_with(chunk)
finally:
? ? ?file_object.close( )
?
讀每行
list_of_all_the_lines = file_object.readlines( )
如果文件是文本文件,還可以直接遍歷文件對象獲取每行:
for line in file_object:
? ? ?process line
?
3.寫文件
寫文本文件
output = open('data', 'w')
?
寫二進(jìn)制文件
output = open('data', 'wb')
?
追加寫文件
output = open('data', 'w+')
?
寫數(shù)據(jù)
file_object = open('thefile.txt', 'w')
file_object.write(all_the_text)
file_object.close( )
?
寫入多行
file_object.writelines(list_of_text_strings)
注意,調(diào)用writelines寫入多行在性能上會比使用write一次性寫入要高。
在處理日志文件的時(shí)候,常常會遇到這樣的情況:日志文件巨大,不可能一次性把整個(gè)文件讀入到內(nèi)存中進(jìn)行處理,例如需要在一臺物理內(nèi)存為 2GB 的機(jī)器上處理一個(gè) 2GB 的日志文件,我們可能希望每次只處理其中 200MB 的內(nèi)容。
在 Python 中,內(nèi)置的 File 對象直接提供了一個(gè) readlines(sizehint) 函數(shù)來完成這樣的事情。以下面的代碼為例:
file = open('test.log', 'r')sizehint = 209715200 ? # 200Mposition = 0lines = file.readlines(sizehint)while not file.tell() - position < 0: ? ? ? position = file.tell() ? ? ? lines = file.readlines(sizehint)
每次調(diào)用 readlines(sizehint) 函數(shù),會返回大約 200MB 的數(shù)據(jù),而且所返回的必然都是完整的行數(shù)據(jù),大多數(shù)情況下,返回的數(shù)據(jù)的字節(jié)數(shù)會稍微比 sizehint 指定的值大一點(diǎn)(除最后一次調(diào)用 readlines(sizehint) 函數(shù)的時(shí)候)。通常情況下,Python 會自動將用戶指定的 sizehint 的值調(diào)整成內(nèi)部緩存大小的整數(shù)倍。
file在python是一個(gè)特殊的類型,它用于在python程序中對外部的文件進(jìn)行操作。在python中一切都是對象,file也不例外,file有file的方法和屬性。下面先來看如何創(chuàng)建一個(gè)file對象:
file(name[, mode[, buffering]])?
file()函數(shù)用于創(chuàng)建一個(gè)file對象,它有一個(gè)別名叫open(),可能更形象一些,它們是內(nèi)置函數(shù)。來看看它的參數(shù)。它參數(shù)都是以字符串的形式傳遞的。name是文件的名字。
mode是打開的模式,可選的值為r w a U,分別代表讀(默認(rèn)) 寫 添加支持各種換行符的模式。用w或a模式打開文件的話,如果文件不存在,那么就自動創(chuàng)建。此外,用w模式打開一個(gè)已經(jīng)存在的文件時(shí),原有文件的內(nèi)容會被清空,因?yàn)橐婚_始文件的操作的標(biāo)記是在文件的開頭的,這時(shí)候進(jìn)行寫操作,無疑會把原有的內(nèi)容給抹掉。由于歷史的原因,換行符在不同的系統(tǒng)中有不同模式,比如在 unix中是一個(gè)\n,而在windows中是‘\r\n’,用U模式打開文件,就是支持所有的換行模式,也就說‘\r’ '\n' '\r\n'都可表示換行,會有一個(gè)tuple用來存貯這個(gè)文件中用到過的換行符。不過,雖說換行有多種模式,讀到python中統(tǒng)一用\n代替。在模式字符的后面,還可以加上+ b t這兩種標(biāo)識,分別表示可以對文件同時(shí)進(jìn)行讀寫操作和用二進(jìn)制模式、文本模式(默認(rèn))打開文件。
buffering如果為0表示不進(jìn)行緩沖;如果為1表示進(jìn)行“行緩沖“;如果是一個(gè)大于1的數(shù)表示緩沖區(qū)的大小,應(yīng)該是以字節(jié)為單位的。
file對象有自己的屬性和方法。先來看看file的屬性。
closed #標(biāo)記文件是否已經(jīng)關(guān)閉,由close()改寫?
encoding #文件編碼?
mode #打開模式?
name #文件名?
newlines #文件中用到的換行模式,是一個(gè)tuple?
softspace #boolean型,一般為0,據(jù)說用于print
file的讀寫方法:
F.read([size]) #size為讀取的長度,以byte為單位?
F.readline([size])?
#讀一行,如果定義了size,有可能返回的只是一行的一部分?
F.readlines([size])?
#把文件每一行作為一個(gè)list的一個(gè)成員,并返回這個(gè)list。其實(shí)它的內(nèi)部是通過循環(huán)調(diào)用readline()來實(shí)現(xiàn)的。如果提供size參數(shù),size是表示讀取內(nèi)容的總長,也就是說可能只讀到文件的一部分。?
F.write(str)?
#把str寫到文件中,write()并不會在str后加上一個(gè)換行符?
F.writelines(seq)?
#把seq的內(nèi)容全部寫到文件中。這個(gè)函數(shù)也只是忠實(shí)地寫入,不會在每行后面加上任何東西。?
file的其他方法:
F.close()?
#關(guān)閉文件。python會在一個(gè)文件不用后自動關(guān)閉文件,不過這一功能沒有保證,最好還是養(yǎng)成自己關(guān)閉的習(xí)慣。如果一個(gè)文件在關(guān)閉后還對其進(jìn)行操作會產(chǎn)生ValueError?
F.flush()?
#把緩沖區(qū)的內(nèi)容寫入硬盤?
F.fileno()?
#返回一個(gè)長整型的”文件標(biāo)簽“?
F.isatty()?
#文件是否是一個(gè)終端設(shè)備文件(unix系統(tǒng)中的)?
F.tell()?
#返回文件操作標(biāo)記的當(dāng)前位置,以文件的開頭為原點(diǎn)?
F.next()?
#返回下一行,并將文件操作標(biāo)記位移到下一行。把一個(gè)file用于for ... in file這樣的語句時(shí),就是調(diào)用next()函數(shù)來實(shí)現(xiàn)遍歷的。?
F.seek(offset[,whence])?
#將文件打操作標(biāo)記移到offset的位置。這個(gè)offset一般是相對于文件的開頭來計(jì)算的,一般為正數(shù)。但如果提供了whence參數(shù)就不一定了,whence可以為0表示從頭開始計(jì)算,1表示以當(dāng)前位置為原點(diǎn)計(jì)算。2表示以文件末尾為原點(diǎn)進(jìn)行計(jì)算。需要注意,如果文件以a或a+的模式打開,每次進(jìn)行寫操作時(shí),文件操作標(biāo)記會自動返回到文件末尾。?
F.truncate([size])?
#把文件裁成規(guī)定的大小,默認(rèn)的是裁到當(dāng)前文件操作標(biāo)記的位置。如果size比文件的大小還要大,依據(jù)系統(tǒng)的不同可能是不改變文件,也可能是用0把文件補(bǔ)到相應(yīng)的大小,也可能是以一些隨機(jī)的內(nèi)容加上去。
?
#! /usr/bin/python
import os,sys
try:
? ? fsock = open("D:/SVNtest/test.py", "r")
except IOError:
? ? print "The file don't exist, Please double check!"
? ? exit()
print 'The file mode is ',fsock.mode
print 'The file name is ',fsock.name
P = fsock.tell()
print 'the postion is %d' %(P)
fsock.close()
#Read file
fsock = open("D:/SVNtest/test.py", "r")
AllLines = fsock.readlines()
#Method 1
for EachLine in fsock:
? ? print EachLine
#Method 2
print 'Star'+'='*30
for EachLine in AllLines:
? ? print EachLine
print 'End'+'='*30
fsock.close()
#write this file
fsock = open("D:/SVNtest/test.py", "a")
fsock.write("""
#Line 1 Just for test purpose
#Line 2 Just for test purpose
#Line 3 Just for test purpose""")
fsock.close()
#check the file status
S1 = fsock.closed
if True == S1:
? ? print 'the file is closed'
else:
? ? print 'The file donot close'
========
Python:文件的讀取、創(chuàng)建、追加、刪除、清空
一、用Python創(chuàng)建一個(gè)新文件,內(nèi)容是從0到9的整數(shù), 每個(gè)數(shù)字占一行:
#python
>>>f=open('f.txt','w') ? ?# r只讀,w可寫,a追加
>>>for i in range(0,10):f.write(str(i)+'\n')
. ?. ?.
>>> f.close()
二、文件內(nèi)容追加,從0到9的10個(gè)隨機(jī)整數(shù):
#python
>>>import random
>>>f=open('f.txt','a')
>>>for i in range(0,10):f.write(str(random.randint(0,9)))
. ?. ?.
>>>f.write('\n')
>>>f.close()
三、文件內(nèi)容追加,從0到9的隨機(jī)整數(shù), 10個(gè)數(shù)字一行,共10行:
#python
>>> import random
>>> f=open('f.txt','a')
>>> for i in range(0,10):
. ?. ?. ? ? for i in range(0,10):f.write(str(random.randint(0,9)))?
. ?. ?. ? ? f.write('\n') ? ?
. ?. ?.
>>> f.close()
四、把標(biāo)準(zhǔn)輸出定向到文件:
#python
>>> import sys
>>> sys.stdout = open("stdout.txt", "w")
>>> ?. . .
?
五、文件的讀寫
一、文件打開:
f = file(name[, mode[, buffering]])
入口參數(shù): ? name 文件名
? ? ? ? ? ? ? ? ? mode ? 選項(xiàng),字符串
? ? ? ? ? ? ? ? ? buffering ? 是否緩沖 (0=不緩沖,1=緩沖, >1的int數(shù)=緩沖區(qū)大小)
返回值 : 文件對象
mode 選項(xiàng):
"r" ? 以讀方式打開,只能讀文件 , 如果文件不存在,會發(fā)生異常 ? ? ?
"w" 以寫方式打開,只能寫文件, 如果文件不存在,創(chuàng)建該文件
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?如果文件已存在,先清空,再打開文件
"rb" ? 以二進(jìn)制讀方式打開,只能讀文件 , 如果文件不存在,會發(fā)生異常 ? ? ?
"wb" 以二進(jìn)制寫方式打開,只能寫文件, 如果文件不存在,創(chuàng)建該文件
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?如果文件已存在,先清空,再打開文件
"rt" ? 以文本讀方式打開,只能讀文件 , 如果文件不存在,會發(fā)生異常 ? ? ?
"wt" 以文本寫方式打開,只能寫文件, 如果文件不存在,創(chuàng)建該文件
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?如果文件已存在,先清空,再打開文件
"rb+" ? 以二進(jìn)制讀方式打開,可以讀、寫文件 , 如果文件不存在,會發(fā)生異常 ? ? ?
"wb+" 以二進(jìn)制寫方式打開,可以讀、寫文件, 如果文件不存在,創(chuàng)建該文件
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?如果文件已存在,先清空,再打開文件
二、關(guān)閉文件
f.close()
當(dāng)文件讀寫完畢后,應(yīng)關(guān)閉文件。
三、清空文件內(nèi)容
f.truncate()
注意:僅當(dāng)以 "r+" ? "rb+" ? ?"w" ? "wb" "wb+"等以可寫模式打開的文件才可以執(zhí)行該功能。
四、文件的指針定位與查詢
(1)文件指針:
? ? ? 文件被打開后,其對象保存在 f 中, 它會記住文件的當(dāng)前位置,以便于執(zhí)行讀、寫操作,這個(gè)位置稱為文件的指針( 一個(gè)從文件頭部開始計(jì)算的字節(jié)數(shù) long 類型 )。
(2)文件打開時(shí)的位置:
? ? ? 以"r" ? "r+" ? "rb+" 讀方式, "w" ? "w+" ? "wb+"寫方式 打開的文件,
? ? ?一開始,文件指針均指向文件的頭部。
(3) 獲取文件指針的值:
? ? ? L = f.tell()
(4) 移動文件的指針
? ? ? ?f.seek( ? 偏移量, 選項(xiàng) )
? ? ? 選項(xiàng) =0 時(shí), 表示將文件指針指向從文件頭部到 "偏移量"字節(jié)處。
? ? ? 選項(xiàng) =1 時(shí), 表示將文件指針指向從文件的當(dāng)前位置,向后移動 "偏移量"字節(jié)。
? ? ? 選項(xiàng) =2 時(shí), 表示將文件指針指向從文件的尾部,,向前移動 "偏移量"字節(jié)。
五、從文件讀取指內(nèi)容 ??
1 文本文件(以"rt"方式打開的文件)的讀取 ?
? ? ? ? ? s = f.readline( ? ? )
? ? ? ? 返回值: s 是字符串,從文件中讀取的一行,含行結(jié)束符。
? ? ? ? 說明: (1) ?如果 len( s ) =0 表示已到文件尾
? ? ? ? ? ? ? ? ? ? (2) ? 如果是文件的最后一行,有可能沒有行結(jié)束符
2 二進(jìn)制文件(以"rb"、"rb+"、"wb+" 方式打開的文件)的讀取 ?
? ? ? ? ? s = f.read( ? ?n )
? ? ?說明: (1) ?如果 len( s ) =0 表示已到文件尾
? ? ? ? ? ? ? ? ? (2) ? 文件讀取后,文件的指針向后移動 len(s) 字節(jié)。
? ? ? ? ? ? ? ? (3)如果磁道已壞,會發(fā)生異常。
六、向文件寫入一個(gè)字符串 ??
? ? f.write( ? ?s )
? ? 參數(shù): ? ? ? s 要寫入的字符串
? ? 說明: (1)文件寫入后,文件的指針向后移動 len(s) 字節(jié)。
? ? ? ? ? ? ? ? ?(2)如果磁道已壞,或磁盤已滿會發(fā)生異常。
返回值: s 是字符串,從文件中讀取的內(nèi)容
七、刪除文件
import os
os.remove(file)
========
Python文件操作讀寫文件
最基本的文件操作當(dāng)然就是在文件中讀寫數(shù)據(jù)。這也是很容易掌握的。現(xiàn)在打開一個(gè)文件以進(jìn)行寫操作:?
1. fileHandle = open ( 'test.txt', 'w' ) ?
fileHandle = open ( 'test.txt', 'w' )?
‘w'是指文件將被寫入數(shù)據(jù),語句的其它部分很好理解。下一步就是將數(shù)據(jù)寫入文件:?
1. fileHandle.write ( 'This is a test.\nReally, it is.' ) ?
fileHandle.write ( 'This is a test.\nReally, it is.' )?
這個(gè)語句將“This is a test.”寫入文件的第一行,“Really, it is.”寫入文件的第二行。最后,我們需要做清理工作,并且關(guān)閉文件:?
1. fileHandle.close() ?
fileHandle.close()?
正如你所見,在Python的面向?qū)ο髾C(jī)制下,這確實(shí)非常簡單。需要注意的是,當(dāng)你再次使用“w”方式在文件中寫數(shù)據(jù),所有原來的內(nèi)容都會被刪除。如果想保留原來的內(nèi)容,可以使用“a”方式在文件中結(jié)尾附加數(shù)據(jù):?
1. fileHandle = open ( 'test.txt', 'a' ) ?
2. fileHandle.write ( '\n\nBottom line.' ) ?
3. fileHandle.close() ?
fileHandle = open ( 'test.txt', 'a' )?
fileHandle.write ( '\n\nBottom line.' )?
fileHandle.close()?
然后,我們讀取test.txt,并將內(nèi)容顯示出來:?
1. fileHandle = open ( 'test.txt' ) ?
2. print fileHandle.read() ?
3. fileHandle.close() ?
fileHandle = open ( 'test.txt' )?
print fileHandle.read()?
fileHandle.close()?
以上語句將讀取整個(gè)文件并顯示其中的數(shù)據(jù)。我們也可以讀取文件中的一行:?
1. fileHandle = open ( 'test.txt' ) ?
2. print fileHandle.readline() # "This is a test." ?
3. fileHandle.close() ?
fileHandle = open ( 'test.txt' )?
print fileHandle.readline() # "This is a test."?
fileHandle.close()?
同時(shí),也可以將文件內(nèi)容保存到一個(gè)list中:?
1. fileHandle = open ( 'test.txt' ) ?
2. fileList = fileHandle.readlines()<div></div> ?
3. for fileLine in fileList: ?
4. ? ? print '>>', fileLine ?
5. fileHandle.close() ?
fileHandle = open ( 'test.txt' )?
fileList = fileHandle.readlines()?
for fileLine in fileList:?
print '>>', fileLine?
fileHandle.close()?
Python在讀取一個(gè)文件時(shí),會記住其在文件中的位置,如下所示:?
1. fileHandle = open ( 'test.txt' ) ?
2. garbage = fileHandle.readline() ?
3. fileHandle.readline() # "Really, it is."fileHandle.close() ?
fileHandle = open ( 'test.txt' )?
garbage = fileHandle.readline()?
fileHandle.readline() # "Really, it is."fileHandle.close()?
可以看到,只有第二行顯示出來。然而,我們可以讓Python從頭開始讀來解決這個(gè)問題:?
1. fileHandle = open ( 'test.txt' ) ?
2. garbage = fileHandle.readline() ?
3. fileHandle.seek ( 0 ) ?
4. print fileHandle.readline() # "This is a test." ?
5. fileHandle.close() ?
fileHandle = open ( 'test.txt' )?
garbage = fileHandle.readline()?
fileHandle.seek ( 0 )?
print fileHandle.readline() # "This is a test."?
fileHandle.close()?
在上面這個(gè)例子中,我們讓Python從文件第一個(gè)字節(jié)開始讀取數(shù)據(jù)。所以,第一行文字顯示了出來。當(dāng)然,我們也可以獲取Python在文件中的位置:?
1. fileHandle = open ( 'test.txt' ) ?
2. print fileHandle.readline() # "This is a test." ?
3. print fileHandle.tell() # "17" ?
4. print fileHandle.readline() # "Really, it is." ?
fileHandle = open ( 'test.txt' )?
print fileHandle.readline() # "This is a test."?
print fileHandle.tell() # "17"?
print fileHandle.readline() # "Really, it is."?
或者在文件中一次讀取幾個(gè)字節(jié)的內(nèi)容:?
1. fileHandle = open ( 'test.txt' ) ?
2. print fileHandle.read ( 1 ) # "T" ?
3. fileHandle.seek ( 4 ) ?
4. print FileHandle.read ( 1 ) # " "(原文有錯(cuò)) ?
fileHandle = open ( 'test.txt' )?
print fileHandle.read ( 1 ) # "T"?
fileHandle.seek ( 4 )?
print FileHandle.read ( 1 ) # " "(原文有錯(cuò))?
在Windows和Macintosh環(huán)境下,有時(shí)可能需要以二進(jìn)制方式讀寫文件,比如圖片和可執(zhí)行文件。此時(shí),只要在打開文件的方式參數(shù)中增加一個(gè)“b”即可:?
1. fileHandle = open ( 'testBinary.txt', 'wb' ) ?
2. fileHandle.write ( 'There is no spoon.' ) ?
3. fileHandle.close() ?
fileHandle = open ( 'testBinary.txt', 'wb' )?
fileHandle.write ( 'There is no spoon.' )?
fileHandle.close()?
1. fileHandle = open ( 'testBinary.txt', 'rb' ) ?
2. print fileHandle.read() ?
3. fileHandle.close() ?
fileHandle = open ( 'testBinary.txt', 'rb' )?
print fileHandle.read()?
fileHandle.close()?
二、從現(xiàn)有文件中獲取信息?
使用Python中的模塊,可以從現(xiàn)有文件中獲取信息。使用“os”模塊和“stat”模塊可以獲取文件的基本信息:?
1. import os ?
2. import stat ?
3. import time<div></div> ?
4. ??
5. fileStats = os.stat ( 'test.txt' ) ?
6. fileInfo = { ?
7. ? ? 'Size' : fileStats [ stat.ST_SIZE ], ?
8. ? ? 'LastModified' : time.ctime ( fileStats [ stat.ST_MTIME ] ), ?
9. ? ? 'LastAccessed' : time.ctime ( fileStats [ stat.ST_ATIME ] ), ?
10. ? ? 'CreationTime' : time.ctime ( fileStats [ stat.ST_CTIME ] ), ?
11. ? ? 'Mode' : fileStats [ stat.ST_MODE ] ?
12. } ?
13. ??
14. for infoField, infoValue in fileInfo: ?
15. ? ? print infoField, ':' + infoValue ?
16. if stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ): ?
17. ? ? print 'Directory. ' ?
18. else: ?
19. ? ? print 'Non-directory.' ?
import os?
import stat?
import time?
fileStats = os.stat ( 'test.txt' )?
fileInfo = {?
'Size' : fileStats [ stat.ST_SIZE ],?
'LastModified' : time.ctime ( fileStats [ stat.ST_MTIME ] ),?
'LastAccessed' : time.ctime ( fileStats [ stat.ST_ATIME ] ),?
'CreationTime' : time.ctime ( fileStats [ stat.ST_CTIME ] ),?
'Mode' : fileStats [ stat.ST_MODE ]?
}?
for infoField, infoValue in fileInfo:?
print infoField, ':' + infoValue?
if stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ):?
print 'Directory. '?
else:?
print 'Non-directory.'?
上面這個(gè)例子創(chuàng)建了一個(gè)包含文件基本信息的dictionary。然后顯示了相關(guān)信息,并且告訴我們打開的是否為目錄。我們也可以試一下打開的是否是其它幾種類型:?
1. import os ?
2. import stat ?
3. ??
4. fileStats = os.stat ( 'test.txt' ) ?
5. fileMode = fileStats [ stat.ST_MODE ] ?
6. if stat.S_ISREG ( fileStats [ stat.ST_MODE ] ): ?
7. ? ? print 'Regular file.' ?
8. elif stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ): ?
9. ? ? print 'Directory.' ?
10. elif stat.S_ISLNK ( fileStats [ stat.ST_MODE ] ): ?
11. ? ? print 'Shortcut.' ?
12. elif stat.S_ISSOCK ( fileStats [ stat.ST_MODE ] ): ?
13. ? ? print 'Socket.' ?
14. elif stat.S_ISFIFO ( fileStats [ stat.ST_MODE ] ): ?
15. ? ? print 'Named pipe.' ?
16. elif stat.S_ISBLK ( fileStats [ stat.ST_MODE ] ): ?
17. ? ? print 'Block special device.' ?
18. elif stat.S_ISCHR ( fileStats [ stat.ST_MODE ] ): ?
19. ? ? print 'Character special device.' ?
import os?
import stat?
fileStats = os.stat ( 'test.txt' )?
fileMode = fileStats [ stat.ST_MODE ]?
if stat.S_ISREG ( fileStats [ stat.ST_MODE ] ):?
print 'Regular file.'?
elif stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ):?
print 'Directory.'?
elif stat.S_ISLNK ( fileStats [ stat.ST_MODE ] ):?
print 'Shortcut.'?
elif stat.S_ISSOCK ( fileStats [ stat.ST_MODE ] ):?
print 'Socket.'?
elif stat.S_ISFIFO ( fileStats [ stat.ST_MODE ] ):?
print 'Named pipe.'?
elif stat.S_ISBLK ( fileStats [ stat.ST_MODE ] ):?
print 'Block special device.'?
elif stat.S_ISCHR ( fileStats [ stat.ST_MODE ] ):?
print 'Character special device.'?
另外,我們可以使用“os.path”來獲取基本信息:?
1. import os.path ?
2. ??
3. fileStats = 'test.txt' ?
4. if os.path.isdir ( fileStats ): ?
5. ? ? print 'Directory.' ?
6. elif os.path.isfile ( fileStats ): ?
7. ? ? print 'File.' ?
8. elif os.path.islink ( fileStats ): ?
9. ? ? print 'Shortcut.' ?
10. elif os.path.ismount ( fileStats ): ?
11. ? ? print 'Mount point.' ?
import os.path?
fileStats = 'test.txt'?
if os.path.isdir ( fileStats ):?
print 'Directory.'?
elif os.path.isfile ( fileStats ):?
print 'File.'?
elif os.path.islink ( fileStats ):?
print 'Shortcut.'?
elif os.path.ismount ( fileStats ):?
print 'Mount point.'?
三、目錄?
和普通文件一樣,關(guān)于目錄的操作也很容易掌握。首先,列出一個(gè)目錄的內(nèi)容:?
1. import os ?
2. ??
3. for fileName in os.listdir ( '/' ): ?
4. ? ? print fileName ?
import os?
for fileName in os.listdir ( '/' ):?
print fileName?
正如你所見,這很簡單,用三行代碼就可以完成。?
創(chuàng)建目錄也很簡單:?
1. import os ?
2. ??
3. os.mkdir ( 'testDirectory' ) ?
import os?
os.mkdir ( 'testDirectory' )?
刪除剛才創(chuàng)建的目錄:?
1. import os ?
2. ??
3. os.rmdir ( 'testDirectory ) ?
import os?
os.rmdir ( 'testDirectory )?
嗯,可以創(chuàng)建多級目錄:?
1. import os ?
2. ??
3. os.makedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' ) ?
import os?
os.makedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )?
如果沒有在創(chuàng)建的文件夾中添加任何東西,就可以一次性將它們?nèi)縿h除(即,刪除所列的所有空文件夾):?
1. import os ?
2. ??
3. os.removedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' ) ?
import os?
os.removedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )?
當(dāng)需要對一個(gè)特定的文件類型進(jìn)行操作時(shí),我們可以選擇“fnmatch”模塊。以下是顯示“.txt”文件的內(nèi)容和“.exe”文件的文件名:?
1. import fnmatch ?
2. import os ?
3. ??
4. for fileName in os.listdir ( '/' ): ?
5. ? ? if fnmatch.fnmath ( fileName, '*.txt' ): ?
6. ? ? ? ? print open ( fileName ).read() ?
7. ? ? elif fnmatch.fnmatch ( fileName, '*.exe' ): ?
8. ? ? ? ? print fileName ?
import fnmatch?
import os?
for fileName in os.listdir ( '/' ):?
if fnmatch.fnmath ( fileName, '*.txt' ):?
print open ( fileName ).read()?
elif fnmatch.fnmatch ( fileName, '*.exe' ):?
print fileName?
“*”字符可以表示任意長度的字符。如果要匹配一個(gè)字符,則使用“?”符號:?
1. import fnmatch ?
2. import os ?
3. ??
4. for fileName in os.listdir ( '/' ): ?
5. ? ? if fnmatch.fnmatch ( fileName, '?.txt' ): ?
6. ? ? ? ? print 'Text file.' ?
import fnmatch?
import os?
for fileName in os.listdir ( '/' ):?
if fnmatch.fnmatch ( fileName, '?.txt' ):?
print 'Text file.'?
“fnmatch”模塊支持正則表達(dá)式:?
1. import fnmatch ?
2. import os ?
3. import re ?
4. ??
5. filePattern = fnmatch.translate ( '*.txt' ) ?
6. for fileName in os.listdir ( '/' ): ?
7. ? ? if re.match ( filePattern, fileName ): ?
8. ? ? ? ? print 'Text file.' ?
import fnmatch?
import os?
import re?
filePattern = fnmatch.translate ( '*.txt' )?
for fileName in os.listdir ( '/' ):?
if re.match ( filePattern, fileName ):?
print 'Text file.'?
若只需要匹配一種類型的文件,更好的辦法是使用“glob”模塊。該模塊的格式和“fnmatch”相似:?
1. import glob ?
2. ??
3. for fileName in glob.glob ( '*.txt' ): ?
4. ? ? print 'Text file.' ?
import glob?
for fileName in glob.glob ( '*.txt' ):?
print 'Text file.'?
使用一定范圍的字符來匹配同樣可行,就像在正則表達(dá)式中使用一樣。假設(shè)你想要顯示擴(kuò)展名前只有一位數(shù)字的文件的文件名:?
1. import glob ?
2. ??
3. for fileName in glob.glob ( '[0-9].txt' ): ?
4. ? ? print filename ?
import glob?
for fileName in glob.glob ( '[0-9].txt' ):?
print filename?
“glob”模塊利用“fnmatch”模塊來實(shí)現(xiàn)。?
四、數(shù)據(jù)編組?
使用前一節(jié)中介紹的模塊,可以實(shí)現(xiàn)在文件中對字符串的讀寫。?
然而,有的時(shí)候,你可能需要傳遞其它類型的數(shù)據(jù),如list、tuple、dictionary和其它對象。在Python中,你可以使用Pickling來完成。你可以使用Python標(biāo)準(zhǔn)庫中的“pickle”模塊完成數(shù)據(jù)編組。?
下面,我們來編組一個(gè)包含字符串和數(shù)字的list:?
1. import pickle ?
2. ??
3. fileHandle = open ( 'pickleFile.txt', 'w' ) ?
4. testList = [ 'This', 2, 'is', 1, 'a', 0, 'test.' ] ?
5. pickle.dump ( testList, fileHandle ) ?
6. fileHandle.close() ?
import pickle?
fileHandle = open ( 'pickleFile.txt', 'w' )?
testList = [ 'This', 2, 'is', 1, 'a', 0, 'test.' ]?
pickle.dump ( testList, fileHandle )?
fileHandle.close()?
拆分編組同樣不難:?
1. import pickle ?
2. ??
3. fileHandle = open ( 'pickleFile.txt' ) ?
4. testList = pickle.load ( fileHandle ) ?
5. fileHandle.close() ?
import pickle?
fileHandle = open ( 'pickleFile.txt' )?
testList = pickle.load ( fileHandle )?
fileHandle.close()?
現(xiàn)在試試存儲更加復(fù)雜的數(shù)據(jù):?
1. import pickle ?
2. ??
3. fileHandle = open ( 'pickleFile.txt', 'w' ) ?
4. testList = [ 123, { 'Calories' : 190 }, 'Mr. Anderson', [ 1, 2, 7 ] ] ?
5. pickle.dump ( testList, fileHandle ) ?
6. fileHandle.close() ?
import pickle?
fileHandle = open ( 'pickleFile.txt', 'w' )?
testList = [ 123, { 'Calories' : 190 }, 'Mr. Anderson', [ 1, 2, 7 ] ]?
pickle.dump ( testList, fileHandle )?
fileHandle.close()?
1. import pickle ?
2. ??
3. fileHandle = open ( 'pickleFile.txt' ) ?
4. testList = pickle.load ( fileHandle ) ?
5. fileHandle.close() ?
import pickle?
fileHandle = open ( 'pickleFile.txt' )?
testList = pickle.load ( fileHandle )?
fileHandle.close()?
如上所述,使用Python的“pickle”模塊編組確實(shí)很簡單。眾多對象可以通過它來存儲到文件中。如果可以的話,“cPickle”同樣勝任這個(gè)工作。它和“pickle”模塊一樣,但是速度更快:?
1. import cPickle ?
2. ??
3. fileHandle = open ( 'pickleFile.txt', 'w' ) ?
4. cPickle.dump ( 1776, fileHandle ) ?
5. fileHandle.close() ?
import cPickle?
fileHandle = open ( 'pickleFile.txt', 'w' )?
cPickle.dump ( 1776, fileHandle )?
fileHandle.close()?
五、創(chuàng)建“虛擬”文件?
你用到的許多模塊包含需要文件對象作為參數(shù)的方法。但是,有時(shí)創(chuàng)建并使用一個(gè)真實(shí)的文件并讓人感到有些麻煩。所幸的是,在Python中,你可以使用“StringIO”模塊來創(chuàng)建文件并將其保存在內(nèi)存中:?
1. import StringIO ?
2. ??
3. fileHandle = StringIO.StringIO ( "Let freedom ring" ) ?
4. print fileHandle.read() # "Let freedom ring." ?
5. fileHandle.close() ?
import StringIO?
fileHandle = StringIO.StringIO ( "Let freedom ring" )?
print fileHandle.read() # "Let freedom ring."?
fileHandle.close()?
cStringIO”模塊同樣有效。它的使用方法和“StringIO”一樣,但就像“cPickle”之于“pickle”,它速度更快:?
1. import cStringIO ?
2. ??
3. fileHandle = cStringIO.cStringIO ( "To Kill a Mockingbird" ) ?
4. print fileHandle.read() # "To Kill a Mockingbid" ?
5. fileHandle.close() ?
import cStringIO?
fileHandle = cStringIO.cStringIO ( "To Kill a Mockingbird" )?
print fileHandle.read() # "To Kill a Mockingbid"?
fileHandle.close()?
結(jié)論?
文件管理,是眾多編程語言的程序員在編寫應(yīng)用程序是經(jīng)常遇到的問題。幸好,和其它語言相比,Python使其出乎意料地容易。Python的標(biāo)準(zhǔn)庫中提供了許多相關(guān)的模塊幫助程序員解決這方面的問題,而它的面向?qū)ο蟮臋C(jī)制也簡化了操作。?
好了,現(xiàn)在你已經(jīng)了解了Python中文件管理的基本知識,可以在今后的應(yīng)用程序中很好地使用了。?
========
python逐行讀取文件內(nèi)容的三種方法
方法一:
復(fù)制代碼 代碼如下:
f = open("foo.txt") ? ? ? ? ? ? # 返回一個(gè)文件對象 ?
line = f.readline() ? ? ? ? ? ? # 調(diào)用文件的 readline()方法 ?
while line: ?
? ? print line, ? ? ? ? ? ? ? ? # 后面跟 ',' 將忽略換行符 ?
? ? # print(line, end = '') # 在 Python 3中使用 ?
? ? line = f.readline() ?
f.close() ?
方法二:
復(fù)制代碼 代碼如下:
for line in open("foo.txt"): ?
? ? print line, ?
方法三:
復(fù)制代碼 代碼如下:
f = open("c:\\1.txt","r") ?
lines = f.readlines()#讀取全部內(nèi)容 ?
for line in lines ?
? ? print line ?
========
python文件和目錄操作方法大全(含實(shí)例)
這篇文章主要介紹了python文件和目錄的操作方法,簡明總結(jié)了文件和目錄操作中常用的模塊、方法,并列舉了一個(gè)綜合實(shí)例,
一、python中對文件、文件夾操作時(shí)經(jīng)常用到的os模塊和shutil模塊常用方法。
1.得到當(dāng)前工作目錄,即當(dāng)前Python腳本工作的目錄路徑: os.getcwd()
2.返回指定目錄下的所有文件和目錄名:os.listdir()
3.函數(shù)用來刪除一個(gè)文件:os.remove()
4.刪除多個(gè)目錄:os.removedirs(r“c:\python”)
5.檢驗(yàn)給出的路徑是否是一個(gè)文件:os.path.isfile()
6.檢驗(yàn)給出的路徑是否是一個(gè)目錄:os.path.isdir()
7.判斷是否是絕對路徑:os.path.isabs()
8.檢驗(yàn)給出的路徑是否真地存:os.path.exists()
9.返回一個(gè)路徑的目錄名和文件名:os.path.split() ? ? eg os.path.split('/home/swaroop/byte/code/poem.txt') 結(jié)果:('/home/swaroop/byte/code', 'poem.txt')?
10.分離擴(kuò)展名:os.path.splitext()
11.獲取路徑名:os.path.dirname()
12.獲取文件名:os.path.basename()
13.運(yùn)行shell命令: os.system()
14.讀取和設(shè)置環(huán)境變量:os.getenv() 與os.putenv()
15.給出當(dāng)前平臺使用的行終止符:os.linesep ? ?Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'
16.指示你正在使用的平臺:os.name ? ? ? 對于Windows,它是'nt',而對于Linux/Unix用戶,它是'posix'
17.重命名:os.rename(old, new)
18.創(chuàng)建多級目錄:os.makedirs(r“c:\python\test”)
19.創(chuàng)建單個(gè)目錄:os.mkdir(“test”)
20.獲取文件屬性:os.stat(file)
21.修改文件權(quán)限與時(shí)間戳:os.chmod(file)
22.終止當(dāng)前進(jìn)程:os.exit()
23.獲取文件大小:os.path.getsize(filename)
二、文件操作方法大全:
1.os.mknod("test.txt") ? ? ? ? ? ? #創(chuàng)建空文件
2.fp = open("test.txt",w) ? ? ? ? ?#直接打開一個(gè)文件,如果文件不存在則創(chuàng)建文件
3.關(guān)于open 模式:
復(fù)制代碼 代碼如下:
w:以寫方式打開,
a:以追加模式打開 (從 EOF 開始, 必要時(shí)創(chuàng)建新文件)
r+:以讀寫模式打開
w+:以讀寫模式打開 (參見 w )
a+:以讀寫模式打開 (參見 a )
rb:以二進(jìn)制讀模式打開
wb:以二進(jìn)制寫模式打開 (參見 w )
ab:以二進(jìn)制追加模式打開 (參見 a )
rb+:以二進(jìn)制讀寫模式打開 (參見 r+ )
wb+:以二進(jìn)制讀寫模式打開 (參見 w+ )
ab+:以二進(jìn)制讀寫模式打開 (參見 a+ )
fp.read([size]) ? ? ? ? ? ? ? ? ? ? #size為讀取的長度,以byte為單位
fp.readline([size]) ? ? ? ? ? ? ? ? #讀一行,如果定義了size,有可能返回的只是一行的一部分
fp.readlines([size]) ? ? ? ? ? ? ? ?#把文件每一行作為一個(gè)list的一個(gè)成員,并返回這個(gè)list。其實(shí)它的內(nèi)部是通過循環(huán)調(diào)用readline()來實(shí)現(xiàn)的。如果提供size參數(shù),size是表示讀取內(nèi)容的總長,也就是說可能只讀到文件的一部分。
fp.write(str) ? ? ? ? ? ? ? ? ? ? ? #把str寫到文件中,write()并不會在str后加上一個(gè)換行符
fp.writelines(seq) ? ? ? ? ? ? ? ? ?#把seq的內(nèi)容全部寫到文件中(多行一次性寫入)。這個(gè)函數(shù)也只是忠實(shí)地寫入,不會在每行后面加上任何東西。
fp.close() ? ? ? ? ? ? ? ? ? ? ? ? ?#關(guān)閉文件。python會在一個(gè)文件不用后自動關(guān)閉文件,不過這一功能沒有保證,最好還是養(yǎng)成自己關(guān)閉的習(xí)慣。 ?如果一個(gè)文件在關(guān)閉后還對其進(jìn)行操作會產(chǎn)生ValueError
fp.flush() ? ? ? ? ? ? ? ? ? ? ? ? ?#把緩沖區(qū)的內(nèi)容寫入硬盤
fp.fileno() ? ? ? ? ? ? ? ? ? ? ? ? #返回一個(gè)長整型的”文件標(biāo)簽“
fp.isatty() ? ? ? ? ? ? ? ? ? ? ? ? #文件是否是一個(gè)終端設(shè)備文件(unix系統(tǒng)中的)
fp.tell() ? ? ? ? ? ? ? ? ? ? ? ? ? #返回文件操作標(biāo)記的當(dāng)前位置,以文件的開頭為原點(diǎn)
fp.next() ? ? ? ? ? ? ? ? ? ? ? ? ? #返回下一行,并將文件操作標(biāo)記位移到下一行。把一個(gè)file用于for … in file這樣的語句時(shí),就是調(diào)用next()函數(shù)來實(shí)現(xiàn)遍歷的。
fp.seek(offset[,whence]) ? ? ? ? ? ?#將文件打操作標(biāo)記移到offset的位置。這個(gè)offset一般是相對于文件的開頭來計(jì)算的,一般為正數(shù)。但如果提供了whence參數(shù)就不一定了,whence可以為0表示從頭開始計(jì)算,1表示以當(dāng)前位置為原點(diǎn)計(jì)算。2表示以文件末尾為原點(diǎn)進(jìn)行計(jì)算。需要注意,如果文件以a或a+的模式打開,每次進(jìn)行寫操作時(shí),文件操作標(biāo)記會自動返回到文件末尾。
fp.truncate([size]) ? ? ? ? ? ? ? ? #把文件裁成規(guī)定的大小,默認(rèn)的是裁到當(dāng)前文件操作標(biāo)記的位置。如果size比文件的大小還要大,依據(jù)系統(tǒng)的不同可能是不改變文件,也可能是用0把文件補(bǔ)到相應(yīng)的大小,也可能是以一些隨機(jī)的內(nèi)容加上去。
三、目錄操作方法大全
1.創(chuàng)建目錄
os.mkdir("file") ? ? ? ? ? ? ? ? ??
2.復(fù)制文件:
shutil.copyfile("oldfile","newfile") ? ? ? ?#oldfile和newfile都只能是文件
shutil.copy("oldfile","newfile") ? ? ? ? ? ?#oldfile只能是文件夾,newfile可以是文件,也可以是目標(biāo)目錄
3.復(fù)制文件夾:
4.shutil.copytree("olddir","newdir") ? ? ? ?#olddir和newdir都只能是目錄,且newdir必須不存在
5.重命名文件(目錄)
os.rename("oldname","newname") ? ? ? ? ? ? ?#文件或目錄都是使用這條命令
6.移動文件(目錄)
shutil.move("oldpos","newpos") ??
7.刪除文件
os.remove("file")
8.刪除目錄
os.rmdir("dir") ? ? ? ? ? ? ? ? ? ? ? ? ? ? #只能刪除空目錄
shutil.rmtree("dir") ? ? ? ? ? ? ? ? ? ? ? ?#空目錄、有內(nèi)容的目錄都可以刪
9.轉(zhuǎn)換目錄
os.chdir("path") ? ? ? ? ? ? ? ? ? ? ? ? ? ?#換路徑
四、文件綜合操作實(shí)例
將文件夾下所有圖片名稱加上'_fc'
python代碼:
復(fù)制代碼 代碼如下:
# -*- coding:utf-8 -*-
import re
import os
import time
#str.split(string)分割字符串
#'連接符'.join(list) 將列表組成字符串
def change_name(path):
? ? global i
? ? if not os.path.isdir(path) and not os.path.isfile(path):
? ? ? ? return False
? ? if os.path.isfile(path):
? ? ? ? file_path = os.path.split(path) #分割出目錄與文件
? ? ? ? lists = file_path[1].split('.') #分割出文件與文件擴(kuò)展名
? ? ? ? file_ext = lists[-1] #取出后綴名(列表切片操作)
? ? ? ? img_ext = ['bmp','jpeg','gif','psd','png','jpg']
? ? ? ? if file_ext in img_ext:
? ? ? ? ? ? os.rename(path,file_path[0]+'/'+lists[0]+'_fc.'+file_ext)
? ? ? ? ? ? i+=1 #注意這里的i是一個(gè)陷阱
? ? ? ? #或者
? ? ? ? #img_ext = 'bmp|jpeg|gif|psd|png|jpg'
? ? ? ? #if file_ext in img_ext:
? ? ? ? # ? ?print('ok---'+file_ext)
? ? elif os.path.isdir(path):
? ? ? ? for x in os.listdir(path):
? ? ? ? ? ? change_name(os.path.join(path,x)) #os.path.join()在路徑處理上很有用
img_dir = 'D:\\xx\\xx\\images'
img_dir = img_dir.replace('\\','/')
start = time.time()
i = 0
change_name(img_dir)
c = time.time() - start
print('程序運(yùn)行耗時(shí):%0.2f'%(c))
print('總共處理了 %s 張圖片'%(i))
輸出結(jié)果:
復(fù)制代碼 代碼如下:
程序運(yùn)行耗時(shí):0.11
總共處理了 109 張圖片
========
Python按行讀文件
1. 最基本的讀文件方法:
# File: readline-example-1.py
?
file = open("sample.txt")
?
while 1:
? ? line = file.readline()
? ? if not line:
? ? ? ? break
? ? pass # do something
一行一行得從文件讀數(shù)據(jù),顯然比較慢;不過很省內(nèi)存。
在我的機(jī)器上讀10M的sample.txt文件,每秒大約讀32000行
2. 用fileinput模塊
# File: readline-example-2.py
?
import fileinput
?
for line in fileinput.input("sample.txt"):
? ? pass
寫法簡單一些,不過測試以后發(fā)現(xiàn)每秒只能讀13000行數(shù)據(jù),效率比上一種方法慢了兩倍多……
3. 帶緩存的文件讀取
# File: readline-example-3.py
?
file = open("sample.txt")
?
while 1:
? ? lines = file.readlines(100000)
? ? if not lines:
? ? ? ? break
? ? for line in lines:
? ? ? ? pass # do something
這個(gè)方法真的更好嗎?事實(shí)證明,用同樣的數(shù)據(jù)測試,它每秒可以讀96900行數(shù)據(jù)!效率是第一種方法的3倍,第二種方法的7倍!
————————————
在Python 2.2以后,我們可以直接對一個(gè)file對象使用for循環(huán)讀每行數(shù)據(jù):
# File: readline-example-5.py
?
file = open("sample.txt")
?
for line in file:
? ? pass # do something
而在Python 2.1里,你只能用xreadlines迭代器來實(shí)現(xiàn):
# File: readline-example-4.py
?
file = open("sample.txt")
?
for line in file.xreadlines():
? ? pass # do something
========
總結(jié)
以上是生活随笔為你收集整理的Python文件操作学习总结的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: XSS 代码总结
- 下一篇: websocket python爬虫_p