Python 中的檔案操作
阿新 • • 發佈:2019-02-06
python中對於資料輸入輸出的處理和常規性語言類似。主要包括:系統輸入輸出、檔案儲存、資料庫儲存等,其中資料儲存讀取操作中主要就是對於檔案和資料庫的處理方面。python中對於檔案的處理提供了一個比較常用且比較方便的內建類file,通過file可以比較方便的對檔案操作。python中對於檔案的操作較多的方法可以很方便的實現檔案的讀取、寫入、刪除、查詢等操作,如下示例:
#!/usr/bin/env python
#-*-encoding:utf-8-*-
import sys,fileinput,codecs
testFile = file('testFile.txt')
# 檔案讀操作
# print testFile.read()
# 檔案單行讀操作.
print testFile.readline()
# 檔案單行制定字元讀操作.
print testFile.readline(3)
# 檔案讀所有行,並返回一個list.
# print testFile.readlines()
print "file name:",testFile.name
# 檔案迭代
print testFile.next()
print next(testFile)
# 返回一個整型的檔案描述符,可供底層作業系統呼叫.
print testFile.fileno()
try:
testFile.write("test")
except Exception as e:
print e
# 關閉檔案
testFile.close()
# with open(name="testFile.txt",mode='wb+',buffering=1024) as testFile:
# testFile.write("print \"append mode------------------------------ 1\"")
# print testFile.read()
with open(name="testFile.txt",mode='a+') as testFile:
testFile.write("print \"append mode------------------------------2 \"" )
testFile.flush()
testFile.seek(0)
for line in testFile:
print "line:",line
# fileinput
testFile = fileinput.input('testFile.txt')
for line in testFile:
print line
testFile.close()
break
# print testFile.filename()
# codecs
with codecs.open('testFile.txt','rb',encoding='utf-8') as testFile:
print '\n\n\n'
print testFile.read(10)
# print help(open)
# print file.__doc__
蔡海飛
123
file name: testFile.txt
456
pwd
87
File not open for writing
line: 蔡海飛
line: 123456
line: pwd
line: 男
line: 1992print "append mode------------------------------2 "print "append mode------------------------------2 "
蔡海飛
蔡海飛
123456
pwd
python檔案操作,開啟檔案可以通過指定檔案操作的模式型別從而賦予檔案操作的不同許可權,python中對於檔案的模式甚至如下幾個型別:
r
模式’r’為讀模式,一般不制定檔案開啟的模式時預設為讀模式w
模式’w’為寫模式b
模式’b‘為以二進位制格式開啟檔案,該模式一般會和其他模式混合使用如:’rb’、’wb‘,’ab’等a
模式’a’為追加模式,一般特指寫模式的追加,一般的寫模式’w’執行寫操作時若檔案存在則直接覆蓋(指標指向開始位置),若不存在則建立,而’a’模式下的檔案寫操作則是若檔案存在,則指標指向檔案結尾追加寫入,若檔案不存在則建立。
同時允許通過在模式後新增一個’+’來來實現檔案的讀寫。如’r+’、’rb+’、’w+’、’wb+‘、’a+‘、’ab+‘。檔案開啟還有一個引數是設定檔案的buffering的,當buffering為0表示不設定快取,buffering為1則表示快取為一行,當其他大於1的數字則表示快取的大小。如上,檔案的開啟可以使用系統自帶的內建類file或者內建函式open函式,也可以通過fileinput模組或者codecs(可以對檔案開啟設定編碼)模組進行開啟。