python 檔案操作

2021-08-04 02:25:55 字數 1765 閱讀 4206



###############################python

檔案操作##########################################

1,檔案讀寫的認識:

1)python 內建了讀寫檔案的函式,用法和c是相容的

2)作業系統不允許普通的程式直接操作磁碟,所以,讀寫檔案:請求作業系統開啟乙個檔案物件(又稱檔案描述符),然後,通過作業系統提供的介面從這個檔案物件操作;

2,檔案讀寫的方式:

1)- 開啟檔案 f = open('filename',mode)

open函式的模式(mode)

r 以讀的方式開啟,定位到檔案開頭, 預設的mode

r+ 以讀寫的方式開啟,定位檔案開頭, 可以寫入內容到檔案

w 以寫的方式開啟,開啟檔案的時候會清空檔案的內容,並且不能讀

w+ 以讀寫的方式開啟,定位到檔案頭,並且開啟檔案的時候也會清空檔案的內容,如果檔案沒有,會建立乙個。

a 以寫的方式開啟,定位到檔案的末尾,是乙個追加的操作, 但並不允許讀

a+ 以讀寫的方式開啟,定位到檔案的末尾,追加的方式。

在使用以上mode 開啟檔案的時候,如果增加了b 模式,表示以二進位制方式開啟

**示例:

f = open('elepha')

f = open('elepha','w') ###會刪除原始檔內容,重新寫入'hello'到檔案中

2)- 對檔案操作 :read,write,readlines,writelines,readline

示例:f.write('hello')

3)- 關閉檔案 f.close()

f.close()

3,檔案的其他操作

f.flush()

f.seek(x,y)##x,表示偏移量。0,不偏移;>0,向右偏移量;<0,向左偏移量。

##y,偏移開始位置。0,從開始的位置;1,從當前的位置;2,從末尾

4.with關鍵字(開啟後,操作完畢後,自動關閉)

with open('filename') as f:

print f.read()

5.程式示例:

*******示例

1)import time

def timmer(func):

def dec():

start_time = time.time()

func()

stop_time = time.time()

#return "%s run %fs"%(func.__name__,stop_time-start_time)

log=open('log','a+')

log.write("%s run %f s\n"%(func.__name__,stop_time-start_time))

log.close()

return "%s run %f s \n"%(func.__name__,stop_time-start_time)

return dec

@timmer#hello1 =timmer(hello1)

def hello1():

print 'hello1...'

time.sleep(1)

@timmer##hello2 =timmer(hello2)

def hello2():

print 'hello2...'

time.sleep(2)

print hello1()

print hello2(

python 檔案操作

簡明 python 教程 中的例子,python 執行出錯,用open代替file 可以執行。poem programming is fun when the work is done if you wanna make your work also fun use python f open e ...

python檔案操作

1,將乙個路徑名分解為目錄名和檔名兩部分 a,b os.path.split c 123 456 test.txt print a print b 顯示 c 123 456 test.txt 2,分解檔名的副檔名 a,b os.path.splitext c 123 456 test.txt pri...

Python 檔案操作

1.開啟檔案 如下 f open d test.txt w 說明 第乙個引數是檔名稱,包括路徑 第二個引數是開啟的模式mode r 唯讀 預設。如果檔案不存在,則丟擲錯誤 w 只寫 如果檔案 不存在,則自動建立檔案 a 附加到檔案末尾 r 讀寫 如果需要以二進位制方式開啟檔案,需要在mode後面加上...