python总结教程_python基础教程总结10——文件
1.打開文件
open(name[mode[,buffing]) ? ?參數: ?文件,模式,緩沖
1)name: 是強制選項,模式和緩沖是可選的
#如果文件不在,會報下面錯誤
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'二進制模式(可添加到其他模式中使用)
’+'讀/寫模式(可添加到其他模塊中使用)
NOTE:
默認的方式,比如說open('filename')是讀模式
r+, 則表示可讀寫
如果是二進制文件或圖形文件,則必須用緩沖模式
普通的w模式會覆蓋文件的內容,a模式則不會.
rb則可以用來讀取二進制文件.
通過參數模式中使用U參數,能夠在打開文件時使用通用的換行符支持模式,無論\r,\n\r,都會換成\n,而不用考慮運行的平臺.
3)緩沖
0或者False: 無緩沖,所有操作直接針對硬盤
1或者True: ?有緩沖,內存代替硬盤,速度快,只有close,flush才寫入硬盤同步.
> 1 ?: ?表示緩沖區的大小
-1 ? ?: ?表示默認的緩沖區大小
2.文件方法
2.1 讀寫
#對空文件來說: 提供寫時,會在已在字符串末尾追加,
1 >>> f = open('somefile.txt','w')2 >>> f.write('Hello,')3 >>> f.write('World!')4 >>>f.close()5 #somefile.txt文件內容
6 Hello,World!
#對于非空文件:提供w方法時,會覆蓋文件中的內容
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文件內容
6 This is1st line.7 This is 2nd line.
簡單讀取的例子:
1 >>> f = open('somefile.txt','r')2 >>> f.read(16)#先讀取16個字符
3 'This is 1st line'
4 >>> f.read() #會讀取剩下的內容,除非seek定位到0,重新讀取
5 '.\nThis is 2nd line.'
6 >>> f.close()
2.2 管道輸出
$ cat somefile.txt | python somescript.py | sort
#一個簡單例子: 統計一個文本中單詞的數量
$ 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)
輸出結果:
# cat somefile.txt | python somescript.py
Word Count: 11
2.3 讀寫行
readline : 讀取行,包括換行符
readlines: 讀取所有行
write: 寫一行, 注意:沒有writeline方法
writelines: 寫多行
NOTE: 如何判斷不同的行以什么結尾? os.linesep
#UNIX
>>> import os
>>> os.linesep
'\n'
#WINDOWS
>>> import os
>>> os.linesep
'\r\n'
2.4 基本文件方法
#測試文本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()
運行文件后,內容如下:
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()
運行后,文件內容如下:
this
isn't a
haiku
2.5 關閉文件
時刻記得close()來關閉文件,這樣做的目的:
安全考慮,防止文件因為某些原因崩潰,寫不進數據
出于數據同步考慮,close(),才會往硬盤中寫數據
出于效率的考慮,內存中的數據可清空一部分出來
為了確保程序結束時close(),可以用try/finally結合使用
# Open your file here
try:
# Write data to your file
finally:
file.close()
NOTE: 一般文件在close()之后才會寫入硬盤,如果想不執行close()方法,又可以看到寫入的內容,那么flush就派上用場了.
3.對文件內容迭代
3.1 按字節處理
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 讀取所有內容
如果文件不是很大,可以用read(),或者readlines()讀取的內容作為字符串來處理.
#用read來迭代每個字符
f = open(r'D:\Work\Python\somefile.txt')
for char in f.read():
process(char)
f.close()
#用readlines來迭代行
f = open(r'D:\Work\Python\somefile.txt','r')
for line in f.readlines():
process(line)
f.close()
3.4 使用fileinput懶惰型迭代
在需要對一個大文件進行迭代時,readlines會占用太多的內存。這個時候可以使用while循環和readline方法來替代。
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來完成關閉的動作,對文件進行迭代,而不使用變量存儲變量,代碼可以更加精簡
for line in open('somefile.txt'):
print line,
#sys.stdin也是可以迭代的
import sys
for line in sys.stdin:
print line,
運行結果:
D:\Work\Python>python file.py
#輸入下面兩行
Hello,World!
Hello,Jerry!
^Z
#按下CTRL+Z鍵后,輸入的內容,顯示
Hello,World!
Hello,Jerry!
#可以對文件迭代器執行和普通迭代器相同的操作。比如將它們轉換為字符串列表,這樣所達到的效果和使用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'
總結
以上是生活随笔為你收集整理的python总结教程_python基础教程总结10——文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php页面添加链接,怎么给一个PHP密码
- 下一篇: 考研数学(180°为什么等于π)