網(wǎng)站首頁 編程語言 正文
一、read
可以一次性讀取文件中所有內(nèi)容
1.txt文件內(nèi)容
??語法:
file.read([size])
例1:file.read():會將所有的內(nèi)容讀取出來
with open('1.txt','r') as file:
content=file.read()
print(content)
執(zhí)行結(jié)果:
file.read():是從文件的頭部開始讀取的。如果想要讀取部分內(nèi)容,可以先使用文件對象的seek()方法將文件的指針移動到新的位置,然后再應(yīng)用read(size)方法讀取。
seek()方法的基本語法格式:
file.seek(offset[,whence])
file:表鎖已經(jīng)打開的文件
offset:用于指定移動的字符個數(shù)
whence:用于指定從什么位置開始計算,值為0表示從文件頭開始計算,1表示從當(dāng)前位置開始計算,2表示從文件末尾開始計算,默認(rèn)為0
例2:讀取部分內(nèi)容
with open('1.txt','r') as file:
file.seek(22)
content=file.read()
print(content)
執(zhí)行結(jié)果:
例3:file.read(size):表示讀取size個字符
with open('1.txt','r') as file:
file.seek(22)
content=file.read(10)
print(content)
執(zhí)行結(jié)果:
二、readline
每次讀取一行數(shù)據(jù)
??格式:
file.readline()
file:打開的文件對象
例4:file.readline()讀取一條數(shù)據(jù)
with open('1.txt','r') as file:
content=file.readline()
print(content)
執(zhí)行結(jié)果:
例5:通過循環(huán)將文件中的數(shù)據(jù)全部讀取出來
with open('1.txt','r') as file:
number=0
while True:
number+=1
content=file.readline()
if content=='':
break
print(number,content,end='\n')
執(zhí)行結(jié)果:
三、readlines
讀取全部行,返回的是一個字符串列表,每個元素為文件的一行內(nèi)容
??語法:
file.readlines()
file:打開的文件
例6:讀取全部行
with open('1.txt','r') as file:
content=file.readlines()
print(content)
執(zhí)行結(jié)果:
例7:將列表元素逐行輸出
with open('1.txt','r') as file:
content=file.readlines()
for index,item in enumerate(content):
print(index,item)
執(zhí)行結(jié)果:
總結(jié)
- .read() 每次讀取整個文件,它通常將讀取到底文件內(nèi)容放到一個字符串變量中,也就是說 .read() 生成文件內(nèi)容是一個字符串類型。
- .readline()每只讀取文件的一行,通常也是讀取到的一行內(nèi)容放到一個字符串變量中,返回str類型。
- .readlines()每次按行讀取整個文件內(nèi)容,將讀取到的內(nèi)容放到一個列表中,返回list類型。
原文鏈接:https://blog.csdn.net/YZL40514131/article/details/125609673
相關(guān)推薦
- 2022-09-15 Python淺析迭代器Iterator的使用_python
- 2022-10-13 pytorch和tensorflow計算Flops和params的詳細(xì)過程_python
- 2022-04-20 Python設(shè)計模式中的結(jié)構(gòu)型適配器模式_python
- 2022-10-24 C語言控制進(jìn)程之進(jìn)程等待詳解_C 語言
- 2022-11-15 Rust使用kind進(jìn)行異常處理(錯誤的分類與傳遞)_相關(guān)技巧
- 2022-08-26 一篇文章搞懂Go語言中的Context_Golang
- 2022-11-09 React特征Form?單向數(shù)據(jù)流示例詳解_React
- 2022-07-20 基于Python操作Excel實戰(zhàn)案例
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支