一、讀取文件
在 Python 中 , 操作文件 的流程如下 :
- 打開文件
- 讀寫文件
- 關閉文件
1、read 函數(shù)
文件打開后 , 可以獲得一個 _io.TextIOWrapper 類型的文件對象 ;
調用 文件對象#read 函數(shù) , 可以 讀取文件對象中的數(shù)據(jù) ;
# 讀取文件中所有數(shù)據(jù)
文件對象.read()
# 讀取文件中 num 字節(jié)數(shù)據(jù)
文件對象.read(num)
read 函數(shù)默認可以讀取文件中的所有數(shù)據(jù) ,
如果為 read 函數(shù)傳入一個數(shù)字作為參數(shù) , 那么讀取指定字節(jié)的數(shù)據(jù) ;
如果調用多次 read 函數(shù) , 后面的 read 會在前面的 read 函數(shù)基礎上進行讀取 ;
2、readline 函數(shù)
調用 文件對象#readline 函數(shù) 可以 一次讀取 文件 一行數(shù)據(jù) ,
返回結果是一個字符串 ;
3、readlines 函數(shù)
調用 文件對象#readlines 函數(shù) 可以 一次性讀取 文件 所有數(shù)據(jù) ,
返回結果是一個列表 ,
列表中的每個元素對應文件中的一行元素 ;
二、代碼示例 - 讀取文件
下面代碼中讀取的文件 file.txt 內容如下 :
Hello World
Tom
Jerry
1、代碼示例 - read 函數(shù)讀取文件 10 字節(jié)內容
代碼示例 :
"""
文件操作 代碼示例
"""
file = open("file.txt", "r", encoding="UTF-8")
print(type(file)) # <class '_io.TextIOWrapper'>
print("read 函數(shù)讀取文件 10 字節(jié)內容: ")
# 讀取文件 10 字節(jié)內容
print(file.read(10))
執(zhí)行結果 :
D:\001_Develop\022_Python\Python39\python.exe D:/002_Project/011_Python/HelloPython/Hello.py
<class '_io.TextIOWrapper'>
read 函數(shù)讀取文件 10 字節(jié)內容:
Hello Worl
Process finished with exit code 0
2、代碼示例 - read 函數(shù)讀取文件所有內容
代碼示例 :
"""
文件操作 代碼示例
"""
file = open("file.txt", "r", encoding="UTF-8")
print(type(file)) # <class '_io.TextIOWrapper'>
print("read 函數(shù)讀取文件所有內容: ")
# 讀取文件所有內容
lines = file.readlines()
print(lines)
for line in lines:
print(line)
執(zhí)行結果 :
D:\001_Develop\022_Python\Python39\python.exe D:/002_Project/011_Python/HelloPython/Hello.py
<class '_io.TextIOWrapper'>
read 函數(shù)讀取文件所有內容:
['Hello World\n', 'Tom\n', 'Jerry']
Hello World
Tom
Jerry
Process finished with exit code 0
3、代碼示例 - readline 函數(shù)讀取文件一行內容
代碼示例 :
"""
文件操作 代碼示例
"""
file = open("file.txt", "r", encoding="UTF-8")
print(type(file)) # <class '_io.TextIOWrapper'>
print("read 函數(shù)讀取文件一行內容: ")
# 讀取文件所有內容
line = file.readline()
print(line)
執(zhí)行結果 :
D:\001_Develop\022_Python\Python39\python.exe D:/002_Project/011_Python/HelloPython/Hello.py
<class '_io.TextIOWrapper'>
read 函數(shù)讀取文件一行內容:
Hello World
Process finished with exit code 0
4、代碼示例 - readlines 函數(shù)讀取文件所有內容
代碼示例 :
"""
文件操作 代碼示例
"""
file = open("file.txt", "r", encoding="UTF-8")
print(type(file)) # <class '_io.TextIOWrapper'>
print("read 函數(shù)讀取文件所有內容: ")
# 讀取文件所有內容
lines = file.readlines()
for line in lines:
print(line)
執(zhí)行結果 :文章來源:http://www.zghlxwxcb.cn/news/detail-491794.html
D:\001_Develop\022_Python\Python39\python.exe D:/002_Project/011_Python/HelloPython/Hello.py
<class '_io.TextIOWrapper'>
read 函數(shù)讀取文件所有內容:
Hello World
Tom
Jerry
Process finished with exit code 0
文章來源地址http://www.zghlxwxcb.cn/news/detail-491794.html
到了這里,關于【Python】文件操作 ② ( 文件操作 | 讀取文件 | read 函數(shù) | readline 函數(shù) | readlines 函數(shù) )的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!