python总结教程_python基础教程总结10——文件
1.打開文件
open(name[mode[,buffing]) ? ?參數(shù): ?文件,模式,緩沖
1)name: 是強(qiáng)制選項(xiàng),模式和緩沖是可選的
#如果文件不在,會(huì)報(bào)下面錯(cuò)誤
1 >>> f = open(r'D:\text.txt','r')2 Traceback (most recent call last):3 File "", line 1, in
4 IOError: [Errno 2] No such file or directory: 'D:\\text.txt'
2)文件模式
'r'讀模式'w'寫模式
’a'追加模式'b'二進(jìn)制模式(可添加到其他模式中使用)
’+'讀/寫模式(可添加到其他模塊中使用)
NOTE:
默認(rèn)的方式,比如說(shuō)open('filename')是讀模式
r+, 則表示可讀寫
如果是二進(jìn)制文件或圖形文件,則必須用緩沖模式
普通的w模式會(huì)覆蓋文件的內(nèi)容,a模式則不會(huì).
rb則可以用來(lái)讀取二進(jìn)制文件.
通過參數(shù)模式中使用U參數(shù),能夠在打開文件時(shí)使用通用的換行符支持模式,無(wú)論\r,\n\r,都會(huì)換成\n,而不用考慮運(yùn)行的平臺(tái).
3)緩沖
0或者False: 無(wú)緩沖,所有操作直接針對(duì)硬盤
1或者True: ?有緩沖,內(nèi)存代替硬盤,速度快,只有close,flush才寫入硬盤同步.
> 1 ?: ?表示緩沖區(qū)的大小
-1 ? ?: ?表示默認(rèn)的緩沖區(qū)大小
2.文件方法
2.1 讀寫
#對(duì)空文件來(lái)說(shuō): 提供寫時(shí),會(huì)在已在字符串末尾追加,
1 >>> f = open('somefile.txt','w')2 >>> f.write('Hello,')3 >>> f.write('World!')4 >>>f.close()5 #somefile.txt文件內(nèi)容
6 Hello,World!
#對(duì)于非空文件:提供w方法時(shí),會(huì)覆蓋文件中的內(nèi)容
1 >>> f = open('somefile','w')2 >>> f.write('This is 1st line.\n')3 >>> f.write('This is 2nd line.')4 >>>f.close()5 #somefile.txt文件內(nèi)容
6 This is1st line.7 This is 2nd line.
簡(jiǎn)單讀取的例子:
1 >>> f = open('somefile.txt','r')2 >>> f.read(16)#先讀取16個(gè)字符
3 'This is 1st line'
4 >>> f.read() #會(huì)讀取剩下的內(nèi)容,除非seek定位到0,重新讀取
5 '.\nThis is 2nd line.'
6 >>> f.close()
2.2 管道輸出
$ cat somefile.txt | python somescript.py | sort
#一個(gè)簡(jiǎn)單例子: 統(tǒng)計(jì)一個(gè)文本中單詞的數(shù)量
$ cat somefile.txt
This is a book!
That is a dog!
Who are you?
腳本清單:
#somescript.py
import sys
text = sys.stdin.read() #讀取所以輸入
words = text.split() #分割字符串
print "Word Count:", len(words)
輸出結(jié)果:
# cat somefile.txt | python somescript.py
Word Count: 11
2.3 讀寫行
readline : 讀取行,包括換行符
readlines: 讀取所有行
write: 寫一行, 注意:沒有writeline方法
writelines: 寫多行
NOTE: 如何判斷不同的行以什么結(jié)尾? os.linesep
#UNIX
>>> import os
>>> os.linesep
'\n'
#WINDOWS
>>> import os
>>> os.linesep
'\r\n'
2.4 基本文件方法
#測(cè)試文本somefile.txt
Welcome to this file
There is nothing here except
This stupid haiku
#首先讀取指定字符 —— ?f.read(n)
>>> f = open(r'd:\Learn\Python\somefile.txt')
>>> f.read(7)
'Welcome'
>>> f.read(4)
' to '
>>> f.close()
#其次讀取所有的行—— f.read()
>>> f = open(r'd:\Learn\Python\somefile.txt','r')
>>> print f.read()
Welcome to this file
There is nothing here except
This stupid haiku
#接著是讀取行 —— f.readline()
>>> f.close()
>>> f = open(r'd:\Learn\Python\somefile.txt')
>>> for i in range(3):
... print str(i) + ':' + f.readline()
...
0:Welcome to this file
1:There is nothing here except
2:This stupid haiku
#再讀取所有行 —— ?f.readlines()
>>> import pprint
>>> pprint.pprint(open('somefile.txt').readlines())
['Welcome to this file\n',
'There is nothing here except\n',
'This stupid haiku']
#下面是寫文件—— f.write(' ......')
>>> f = open(r'somefile.txt','w')
>>> f.write('this\nis no\nhaiku')
>>> f.close()
運(yùn)行文件后,內(nèi)容如下:
this
is no
haiku
#最后是writelines—— f.writelines( ' ....' )
>>> f = open(r'somefile.txt')
>>> lines = f.readlines()
>>> f.close()
>>> lines[1] = "isn't a\n"
>>> f = open('somefile.txt','w')
>>> f.writelines(lines)
>>> f.close()
運(yùn)行后,文件內(nèi)容如下:
this
isn't a
haiku
2.5 關(guān)閉文件
時(shí)刻記得close()來(lái)關(guān)閉文件,這樣做的目的:
安全考慮,防止文件因?yàn)槟承┰虮罎?#xff0c;寫不進(jìn)數(shù)據(jù)
出于數(shù)據(jù)同步考慮,close(),才會(huì)往硬盤中寫數(shù)據(jù)
出于效率的考慮,內(nèi)存中的數(shù)據(jù)可清空一部分出來(lái)
為了確保程序結(jié)束時(shí)close(),可以用try/finally結(jié)合使用
# Open your file here
try:
# Write data to your file
finally:
file.close()
NOTE: 一般文件在close()之后才會(huì)寫入硬盤,如果想不執(zhí)行close()方法,又可以看到寫入的內(nèi)容,那么flush就派上用場(chǎng)了.
3.對(duì)文件內(nèi)容迭代
3.1 按字節(jié)處理
def process(string):
print 'Processing...', string
f = open('somefile.txt')
while True:
char = f.read(1)
if not char:
break
process(char)
f.close()
3.2 按行處理
f = open(filename)
while True:
line = f.readline()
if not line:
break
process(line)
f.close()
3.3 讀取所有內(nèi)容
如果文件不是很大,可以用read(),或者readlines()讀取的內(nèi)容作為字符串來(lái)處理.
#用read來(lái)迭代每個(gè)字符
f = open(r'D:\Work\Python\somefile.txt')
for char in f.read():
process(char)
f.close()
#用readlines來(lái)迭代行
f = open(r'D:\Work\Python\somefile.txt','r')
for line in f.readlines():
process(line)
f.close()
3.4 使用fileinput懶惰型迭代
在需要對(duì)一個(gè)大文件進(jìn)行迭代時(shí),readlines會(huì)占用太多的內(nèi)存。這個(gè)時(shí)候可以使用while循環(huán)和readline方法來(lái)替代。
import fileinput
def process(string):
print 'Processing...', string
for line in fileinput.input('somefile.txt'):
process(line)
3.5 文件迭代器
#Python中文件是可以迭代的
f = open('somefile.txt')
for line in f:
print line,
f.close()
#如果希望Python來(lái)完成關(guān)閉的動(dòng)作,對(duì)文件進(jìn)行迭代,而不使用變量存儲(chǔ)變量,代碼可以更加精簡(jiǎn)
for line in open('somefile.txt'):
print line,
#sys.stdin也是可以迭代的
import sys
for line in sys.stdin:
print line,
運(yùn)行結(jié)果:
D:\Work\Python>python file.py
#輸入下面兩行
Hello,World!
Hello,Jerry!
^Z
#按下CTRL+Z鍵后,輸入的內(nèi)容,顯示
Hello,World!
Hello,Jerry!
#可以對(duì)文件迭代器執(zhí)行和普通迭代器相同的操作。比如將它們轉(zhuǎn)換為字符串列表,這樣所達(dá)到的效果和使用readlines一樣.
>>> f = open('somefile.txt','w')
>>> f.write('First line\n')
>>> f.write('Second line\n')
>>> f.write('Third line\n')
>>> f.close()
>>> lines = list(open('somefile.txt'))
>>> lines
['First line\n', 'Second line\n', 'Third line\n']
>>> first,second,third = open('somefile.txt')
>>> first
'First line\n'
>>> second
'Second line\n'
>>> third
'Third line\n'
總結(jié)
以上是生活随笔為你收集整理的python总结教程_python基础教程总结10——文件的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php页面添加链接,怎么给一个PHP密码
- 下一篇: websocket python爬虫_p