首頁  >  文章  >  後端開發  >  Python是檔案

Python是檔案

王林
王林原創
2024-08-12 18:39:58560瀏覽

Python - files

檔案操作:

  • 檔案讀取
  • 檔案寫入
  • 追加內容

檔案讀取:
以 open('Logs.txt', 'r') 作為檔案:

open 是 python 內建函數,用於開啟檔案。第一個參數是檔名,第二個參數是讀取模式。
with 語句用於自動關閉檔案。這將防止記憶體洩漏,提供更好的資源管理
as file as 關鍵字將開啟的檔案物件指派給變數 file

with open('logs.txt', 'r')as file:
    # print(file, type(file))
    content = file.readlines()
    print(content, type(content))   # this content is a list. Elements are each line in file 
    for line in content:
        print(line, end='') # end='' is defined to avoid \n as list iteration ends already with \n
        #print(line.strip())

輸出:
['這是用於儲存日誌的檔案', '建立於 12.08.2024n', '作者 Suresh Sundararajun']
這是用來儲存日誌的檔案
創建於 12.08.2024
作者 Suresh Sundararaju

  • file.readlines() 將以列表形式給予檔案內容
  • file.readline() 會將第一行作為字串給出

  • 迭代列表,每一行都可以作為字串檢索

  • 迭代後面,每個str都可以作為字元檢索

這裡當透過for迴圈迭代列表時,返回以換行符結束。當用列印語句列印時,又出現了另一行。為了避免使用 strip() 或 end=''

檔案寫入:
以 open('notes.txt','w') 作為檔案:

這與檔案讀取類似。唯一的語法差異是模式被指定為“w”。這裡將建立notes.txt 檔案。

進一步寫入內容,我們可以使用 file.write('Content')
使用寫入模式,每次都會建立檔案並且內容將在該區塊內被覆蓋

# Write in file
with open('notes.txt', 'w') as file:
    i=file.write('1. fILE CREATED\n')
    i=file.write('2. fILE updated\n')

追加到文件中:
以 open('notes.txt', 'a') 作為檔案:

對於追加,mode='a' 與 file.write(str) 或 file.writelines(list) 一起使用。此處現有文件中,內容將在最後更新。

#Append file
with open('notes.txt', 'a') as file:
    file.write('Content appended\n')


#Read all the lines and store in list
with open('notes.txt', 'r') as file:
    appendcontent = file.readlines()
    print(appendcontent)

輸出:
['1.檔案已建立n', '2.檔案已更新', '內容已追加']

註:

  1. 還有一些其他模式可用 'r+','w+','a+'
  2. 可以加例外

以上是Python是檔案的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn