版權所有,未經許可,禁止轉載
章節
- Python 介紹
- Python 開發環境搭建
- Python 語法
- Python 變量
- Python 數值類型
- Python 類型轉換
- Python 字符串(String)
- Python 運算符
- Python 列表(list)
- Python 元組(Tuple)
- Python 集合(Set)
- Python 字典(Dictionary)
- Python If … Else
- Python While 循環
- Python For 循環
- Python 函數
- Python Lambda
- Python 類與對象
- Python 繼承
- Python 迭代器(Iterator)
- Python 模塊
- Python 日期(Datetime)
- Python JSON
- Python 正則表達式(RegEx)
- Python PIP包管理器
- Python 異常處理(Try…Except)
- Python 打開文件(File Open)
- Python 讀文件
- Python 寫文件
- Python 刪除文件與文件夾
打開本地文件
假設在本地當前目錄下有以下文件:
test.txt
High in the halls of the kings who are gone
Jenny would dance with her ghosts
The ones she had lost and the ones she had found
And the ones who had loved her most
The one who'd heen gone for so very long
使用內置的open()
函數打開文件。
open()
函數會返回一個文件對象,它有一個read()
方法用來讀取文件內容:
示例
f = open("test.txt", "r")
print(f.read())
讀取文件的部分內容
默認情況下,read()
方法將讀取全部內容,但也可以指定要讀取多少字符:
示例
讀取文件的前10個字符:
f = open("test.txt", "r")
print(f.read(10))
按行讀取
您可以使用readline()
方法讀取一行:
示例
讀取一行:
f = open("test.txt", "r")
print(f.readline())
通過調用兩次readline()
,可以讀取兩行:
示例
讀取2行:
f = open("test.txt", "r")
print(f.readline())
print(f.readline())
可以通過循環,逐行讀取整個文件:
示例
逐行讀取文件:
f = open("test.txt", "r")
for x in f:
print(x)
關閉文件
當處理完文件后,應該關閉文件,釋放資源。
示例
完成文件處理后,關閉文件:
f = open("test.txt", "r")
print(f.readline())
f.close()
注意: 完成文件處理后,應該關閉文件,釋放資源。某些情況下,由於緩存,對文件所做的更改不會立即顯示,直到關閉文件再重新打開。