open函數 文件操做python
open(路徑+文件名,讀寫模式)
以下:ide
f = open("test.log","a") f.write("8") f.write("9\n") f.close()
使用追加的方式打開test.log 賦值給f,追加89 而後關閉文件函數
經常使用模式有:ui
r:以讀方式打開
w:以寫方式打開
a:以追加模式打開
注意:spa
一、使用'W',文件若存在,首先要清空,而後(從新)建立,指針
二、使用'a'模式 ,把全部要寫入文件的數據都追加到文件的末尾,即便你使用了seek()指向文件的其餘地方,若是文件不存在,將自動被建立。code
f.read([size]) size未指定則返回整個文件,若是文件大小>2倍內存則有問題.f.read()讀到文件尾時返回""(空字串)對象
>>> f = open('anaconda-ks.cfg','r') >>> print f.read(5) #讀取5個字節,不指定則讀取全部 #vers >>> f.close <built-in method close of file object at 0x7f96395056f0>
file.readline() 返回一行blog
file.readline([size]) 若是指定了非負數的參數,則表示讀取指定大小的字節數,包含「\n」字符。內存
>>> f = open('anaconda-ks.cfg','r') >>> print f.readline() #version=DEVEL >>> print f.readline(1) #返回改行的第一個字節,指定size的大小 #
for line in f: print line #經過迭代器訪問
f.write("hello\n") #若是要寫入字符串之外的數據,先將他轉換爲字符串.
f.tell() 返回一個整數,表示當前文件指針的位置(就是到文件頭的比特數).
>>> print f.readline() #version=DEVEL >>> f.tell() 15 >>> f.close
f.seek(偏移量,[起始位置])
用來移動文件指針
偏移量:單位:比特,可正可負
起始位置:0-文件頭,默認值;1-當前位置;2-文件尾
cat foo.txt # This is 1st line # This is 2nd line # This is 3rd line # This is 4th line # This is 5th line #!/usr/bin/python # Open a file f = open("foo.txt", "r") print "Name of the file: ", f.name line = f.readline() print "Read Line----------------------->: %s" % (line) #讀取第一行 print f.tell() #顯示遊標位置 f.seek(38,1) #偏移38個字符 從當前位置開始 注意這裏若是偏移的不是正行是按照當前字節讀取到行尾進行計算的 line = f.readline() print "Read Line: %s" % (line) print f.tell() # Close opend file f.close() python seek.py Name of the file: foo.txt Read Line----------------------->: # This is 1st line 19 Read Line: # This is 4th line 76
f.close() 關閉文件
wiht 方法 爲了不打開文件後忘記關閉,能夠經過with語句來自動管理上下文。
cat seek2.py #!/usr/bin/env python with open('foo.txt','a') as f: f.write('the is new line,hello,world\n') python seek2.py cat foo.txt # This is 1st line # This is 2nd line # This is 3rd line # This is 4th line # This is 5th line the is new line,hello,world