1. 程式人生 > >Python下對檔案的操作

Python下對檔案的操作

檔案

操作檔案的函式/方法

在python中要操作檔案需要記住的1個函式和3個方法

open函式  :開啟檔案,並且返回檔案操作物件
read   :將檔案內容讀取到記憶體
write  :將指定內容寫入檔案
close  :關閉檔案
1.讀取檔案

open()返回一個檔案物件,通常使用兩個變數:open(filename,mode)
‘r’ 只讀
‘r+’ 讀寫
‘w’ 只寫

file = open('file')       ##開啟檔案(file檔案在程式的當前目錄,若需要開啟指定檔案,需要寫絕對路徑)
f = file.read()           ##讀取檔案
print f f = file.read() print f ##第二次讀取不到資訊,由於檔案指標標記由檔案頭到了檔案尾。 ##檔案指標: ### 檔案指標標記從哪個位置開始讀取資料 ### 第一次開啟檔案時,通常檔案指標會指向檔案的開始位置 ### 當執行了read方法後,檔案指標會移動到讀取內容的末尾 file.close() ##如果忘記關閉檔案,會造成系統消耗,而且會影響到後續對檔案的訪問

利用with是一個很好的方法,不需要關閉檔案。(程式執行完成後自動釋放記憶體):

with open('file2'
) as file_object: text = file_object.read() print type(text) ##輸出檔案內容型別 print len(text) ##輸出檔案內容長度 print text

read方法預設會把檔案的所有內容一次性讀到記憶體,如果檔案太大,對記憶體的佔用會非常嚴重。

  • readline方法:
    readline()方法可以一次性讀取一行內容
    方法執行後,會把檔案指標移動到下一行,準備再次讀取
file = open('file')
while True:
    text = file
.readline() if not text: ##當讀取不出內容時 break print text, file.close()
  • seek() 方法用於移動檔案讀取指標到指定位置。

    fileObject.seek(offset[, whence])
    

    offset – 開始的偏移量,也就是代表需要移動偏移的位元組數

whence:可選,預設值為 0。給offset引數一個定義,表示要從哪個位置開始偏移;0代表從檔案開頭開始算起,1代表從當前位置開始算起,2代表從檔案末尾算起。

file:

12345678
asas
dsgvcxvfd
f = open('file','r+')
print f.readline()
f.seek(-4,2)             ##檔案指標偏移到末尾倒數第四個位元組(result-->xvf)
#f.seak(5)               ##檔案指標從開頭偏移到第五個位元組(result-->678)
print f.read(4)          ##從第四個位元組開始讀取
f.close()
2.寫檔案:
file = open('file','w')     ##覆蓋
##file = open('file','a')   ##追加字串
f = file.write('HELLO')
print f
file.close()
with open('file2','w') as file_object:          
    file_object.write('Every day every morning\n')
    file_object.write('My mother my father\n')
3.複製檔案
f = open('file')
text = f.read()
w = open('file2','w')
w.write(text)            
f.close()
w.close()

file = open('file')
file2 = open('file2','w')     ##自定義檔名
while True:                   ##按行寫入
    text = file.readline()
    file2.write(text)
    if not text:
        break
    print text,
file.close()
file2.close()

JSON檔案:

很多程式都要求使用者輸入某種資訊並存儲在列表和字典等資料結構中,為了儲存這些資料,一種簡單的方式是使用模組json來儲存。
在python中使用json的時候,json是以一種良好的格式來進行資料的互動,模組json以更簡單的資料結構轉存到檔案中,並在程式再次執行時載入該檔案中的資料,還可以使用json在Python程式之間分享資料。更重要的是,json資料格式並非Python專用的,這讓你能夠將以json格式儲存的資料與使用其他程式語言的人分享。

讀寫Json檔案:

import json
number = [1,2,3,43,4]

with open('json_file.json','w') as f_obj:
    json.dump(number,f_obj)           ##json寫入資料
import json
filename = 'json_file.json'
with open(filename) as f_obj:
    number = json.load(f_obj)           ##讀取json檔案
print number

例項:儲存使用者資料

import json
filename = "username.json"
try:
    with open(filename) as f_obj:
        username = json.load(f_obj)
except ValueError:
    username = raw_input("What is you name? ")
    with open(filename,"w") as f_obj:
        json.dump(username,f_obj)
        print "We'll remember you when you come back %s" % username
#依賴於try程式碼塊成功執行的程式碼都應放到else程式碼塊中:
else: