1. 程式人生 > >python --- 文件處理

python --- 文件處理

() 文件結尾 部分 wordcount txt eth 打開文件 ring flush

Welcome to No pain No gain ,we are learning together!!

文件和流

python3中使用 open 打開文件,python2.x是file
open(name[,mode[,buffering]])

mode: ‘r‘ 讀模式
‘w‘ 寫模式
‘a‘ 追加模式
‘b‘ 二進制模式
‘r+‘ 等同於 ‘r+a‘
‘w+‘ 等同於 ‘w+r‘
‘a+‘ 等同於 ‘a+r‘

buffering 參數是0或者false, 表示無緩沖區,直接對硬盤進行操作
參數是1或者True , 表示使用內存,程序更快
參數大於1,表示緩沖區的大小,(單位是字節)
-1或者負數,表示使用默認緩存區的大小

操作:f = open(‘somefile.txt‘) #默認的打開模式是read

f = open(‘somefile.txt‘ , ‘w‘)
f.write(‘hello , ‘) #會提示寫入字符的個數
f.write(‘world‘)
f.close() #如果文件存在,直接覆蓋起先的內容,然後寫入,如果是寫的,則新建


f = open(‘somefiles.txt‘ , ‘r‘) #‘r‘模式是默認的模式,可以不用添加
f.read(4) # 告訴流讀取4個字符(字節),會輸出前四個字符
f.read() #讀取剩余的部分,輸出剩余的字符
f.close()



管式輸出: $cat somefile.txt | python somescript.py | sort

#somescript.py
import sys
text = sys.stdin.read()
words = text.split()
wordcount = len(words)
print ‘Wordcount:‘ . wordcount


前面的例子都是按照流從頭往後來處理的。可以用seek 和 tell 來對興趣的部分進行處理


seek(offset[,whence]):
whence = 0 #表示偏移量是在文件的開始進行
whence = 1 #想當與當前位置,offset可以是負值
whence = 2 #相對於文件結尾的移動


f = open(r‘a.txt‘ , ‘w‘)
f.write(‘0123456789‘)
f.seek(5)
f.write(‘hello world‘)
f = open(r‘a.txt‘)
r.read()
‘01234hello world...‘ #會在第五的位置開始寫。


f = open(‘a.txt‘)
f.read(3)
‘012‘
f.read(2)
‘34‘
f.tell()
5l #告訴你在當前第五的位置



f.readline #讀取一行
f=open(‘a.txt‘)
for i in range(3):
print str(i) + ‘:‘ + f.readline()

0:......
1:......
2:.....
3:.....


f.readlines #全部讀取


f.writeline()
f.writelines()







文件的關閉:
關閉文件,可以避免用完系統中所打開文件的配額
如果想確保文件被關閉了,可以使用try/finally 語句,並在finally中調用close()
方法:
open your file here
try:
write data to your file
finally:
file.close()

實際上有專門對這種情況設計的語句 ,既with語句
with open(‘someone.txt‘) as somefile:
do something(someone.txt)
#把文件負值到 somefile變量上,

如果文件正在內存中,還沒有寫入文件中,想要在文件中看到內容,需要用 flush 方法

python --- 文件處理