Python 檔案操作

2021-07-16 23:52:28 字數 1727 閱讀 3850

檔案操作,無外乎讀寫,但首先你要開啟檔案。

f = open(filename, mode)filename是檔名,可以帶目錄;mode是讀寫模式(可以是讀,寫,追加等);f是file handler。

f.close()

注意,write不會自動加入\n,這一點不像print

f = open('myfile.txt', 'w')    # open file for writing

f.write('this is first line\n') # write a line to the file

f.write('this is second line\n') # write one more line

f.close()

總共有三個模式:

讀取所有內容

f = open('myfile.txt', 'r')

f.read()

'this is first line\nthis is second line\n'
f.close()
讀取所有行
f = open('myfile.txt','r')

f.readlines()

['this is first line\n', 'this is second line\n']
f.close()
讀取一行
f = open('myfile.txt','r')

f.readline()

'this is first line\n'
f.close()
f = open('myfile.txt','a')

f.write('this is third line\n')

f.close()
f = open('myfile.txt','r')

for line in f:

print line,

this is first line

this is second line

this is third line

f.close()
with open('myfile.txt','r') as f:

for line in f:

print line,

this first line

this second line

this is third line

with open('myfile.txt','r') as f:

for line in f.readlines():

print line,

this is first line

this is second line

this is third line

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後面加上...