python讀取 寫入檔案

2022-05-09 05:36:12 字數 1354 閱讀 5002

《python程式設計:從入門到實踐》讀書筆記

1.讀取檔案並且對檔案內容進行列印有三種方式:

with open('

test.txt

') as fo:

for lins in

fo:

print

(lins.rstrip())

with open(

'test.txt

') as fo:

lines=fo.read()

print

(lines.rstrip())

with open(

'test.txt

') as fo2:

lt=fo2.readlines()

for l in

lt:

print(l.rstrip())

1)讀取之後使用for迴圈遍歷檔案物件 進行列印

2)直接讀取檔案物件列印。

3)將檔案內容存到列表裡,在with**塊外列印。(需要遍歷列表,rstrip方法是字串的,不是列表的。)

2.將內容寫入到檔案:

直接使用write函式,在open時制定引數'w',寫入時會將原來檔案中所儲存的資訊刪除,重新寫入。

fn='

test.txt

'with open(fn,'w

') as fo:

fo.write(

"hello world

")

可以將開啟方式變為『a』,就是追加檔案內容。r+是可讀可寫。

3.使用while和異常結合實現加法:

a=input('

first:')

b=input('

second:')

while

true:

try:

aa=int(a)

bb=int(b)

c=aa+bb

except

valueerror:

print('

error!!!try again')

a=input('

first:

')//需要重新讀入資料

b=input('

second:')

else

:

print

(c)

break

寫的時候遇見了乙個問題就是死迴圈列印error. 在except中加入continue還是死迴圈。

原因是需要重新讀入資料。

python(檔案讀取寫入)

python讀寫檔案 1.open 使用open開啟檔案後一定要記得呼叫檔案物件的close 方法。比如可以用try finally語句來確保最後能關閉檔案。file object open thefile.txt try all the text file object.read finally ...

python 寫入 讀取txt檔案

with open desc.txt w as f f.write 我是個有想法的小公舉 這句 自帶檔案關閉功能。比較常用的檔案讀寫選項 r 以讀的方式開啟,只能讀檔案,若檔案不存在,則發生異常 w 以寫的方式開啟,只能寫檔案,如果檔案不存在,建立該檔案 如果檔案已存在,先清空,再開啟檔案 rb 以...

python的檔案讀取寫入

讀寫檔案是最常見的io操作。python內建了讀寫檔案的函式,用法和c是相容的。讀寫檔案前,我們先必須了解一下,在磁碟上讀寫檔案的功能都是由作業系統提供的,現代作業系統不允許普通的程式直接操作磁碟,所以,讀寫檔案就是請求作業系統開啟乙個檔案物件 通常稱為檔案描述符 然後,通過作業系統提供的介面從這個...